我解决了“已被 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);
});
我两者都有相同的代码,但解决方案不起作用,我不知道为什么
API是你写的吗? CORS 不是 UI 错误,因此您在此处发布的代码才是正确的。 CORS 是后端错误,可以从后端本身修复。在 CORS 策略中,您可以提供您想要授予访问 API 权限的标头。
因此,对于您的代码,您必须授予对“/users”的访问权限,但尚未授予对“/register”的访问权限。
在API部署过程中,您需要给出CORS策略,就像我在下面定义的CORS策略一样。
<base />
<cors>
<allowed-origins>
<origin>*</origin>
</allowed-origins>
<allowed-methods>
<method>GET</method>
<method>POST</method>
<method>HEAD</method>
<method>OPTIONS</method>
<method>PUT</method>
<method>DELETE</method>
</allowed-methods>
<allowed-headers>
<header>*</header>
</allowed-headers>
</cors>
如果您在这里看到“*”是我的标题部分,这意味着我允许所有标题。
您可以在服务器入口文件的顶部添加此中间件,这样您就不必在每个路由处理程序中重复自己,并且不会错过其中一个:
app.use((req, res, next)=>{
res.header("Access-Control-Allow-Origin", "*");
next();
}
);