这是我为React编写的“测试”代码:
<button
type="button"
onClick={async () => {
try {
console.log(
await fetch("http://localhost:4000/api/auth/signup", {
method: "POST",
body: JSON.stringify({ name: "", password: "", email: "" }),
headers: new Headers({
"Content-Type": "application/json",
}),
})
);
} catch (err) {
console.log("a server error");
}
}}
>
test
</button>
这是我得到的错误
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 400
statusText: "Bad Request"
type: "cors"
url: "http://localhost:4000/api/auth/signup"
我用邮递员测试了应用程序prior,它工作正常。
我还测试了来自同一api的get
请求,它也运行良好。
我错过了什么?
使用您的Ip地址而不是localhost。如下所示
<button
type="button"
onClick={async () => {
try {
console.log(
await fetch("http://[Your Ip Address]:4000/api/auth/signup", {
method: "POST",
body: JSON.stringify({ name: "", password: "", email: "" }),
headers: new Headers({
"Content-Type": "application/json",
}),
})
);
} catch (err) {
console.log("a server error");
}
}}
>
test
</button>