【发布时间】:2021-12-25 17:30:51
【问题描述】:
我解决了“已被 CORS 策略阻止”错误,但有一些我不明白的地方,我在 api 部分添加了一个标头,它在我的登录表单中成功运行,但在注册部分,我的代码给出“已被 CORS 策略阻止”错误,我不明白原因。
无错误部分
客户端代码
await axios.post(
url + detailsLogin.email).then(function (response) {
console.log("data", response);
if (detailsLogin.email === response.data.email && detailsLogin.password === response.data.password) {
console.log("Logged in!");
setLogined(true);
}
else {
console.log("Details do not match")
setError("Details do not match!" )
}
})
.catch(function (response) {
//handle error
console.log("Details do not match", response)
setError("Details do not match!")
});
};
简单的api代码
app.post("/users/:email", (req, res) => {
const user = db.find((u) => u.email == req.params.email);
res.header("Access-Control-Allow-Origin", "*");
if (user) {
res.status(200).send(user);
} else {
res.status(404).send({
message: "User is not found..",
});
}
});
错误的部分
客户端代码
const body = { email: email, name: name, password: password };
const url = "http://localhost:3002/register";
axios.post(url, body
).then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
简单的api代码
app.post("/register", (req, res) => {
res.header("Access-Control-Allow-Origin", "*");
const willSaveData = {
id: new Date().getTime(),
email: req.body.email,
name: req.body.name,
password: req.body.password,
};
db.push(willSaveData);
console.log(willSaveData, "from DB");
res.status(200).send(willSaveData);
});
当我尝试将标题部分提供给 axios 时,我也不断收到错误消息。像这样 ->
axios.post(url, body,{headers: { 'Content-Type': 'application/json'}}
).then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
我在两者中都有相同的代码,但解决方案不起作用,我不知道为什么
【问题讨论】:
标签: node.js reactjs axios cross-domain expires-header