【问题标题】:react - axios - api has been blocked by CORS policy errorreact - axios - api 已被 CORS 策略错误阻止
【发布时间】: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


    【解决方案1】:

    是你写的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>
    

    如果您在这里看到“*”是我的标题部分,这意味着我允许所有标题。

    【讨论】:

      【解决方案2】:

      谢谢大家,我解决了这个问题。

      我在我的项目中包含了cors middleware 并使用了:

      app.use((req, res, next)=>{
        app.options('*', cors())
        next();
       }
      );
      

      但这次用户部分停止工作,所以我补充说:

      res.header("Access-Control-Allow-Origin", "*");
      

      现在这是一个有点奇怪的解决方案,但我的代码在双方都有效。

      【讨论】:

        猜你喜欢
        • 2021-10-13
        • 2020-08-27
        • 2018-07-20
        • 1970-01-01
        • 2019-10-01
        • 2019-08-04
        • 2020-05-28
        • 1970-01-01
        • 2021-01-07
        相关资源
        最近更新 更多