【问题标题】:How to connect front and backend如何连接前端和后端
【发布时间】:2021-07-06 12:35:26
【问题描述】:

我尝试将本地后端与前端连接

   axios({
      method: "post",
      url: "http://localhost:5000/api/user/login",
      withCredentials: true,
      data: {
        email,
        password,
      },
    })
      .then((res) => {
        if (res.data.errors) {
          emailError.innerHTML = res.data.errors.email;
          passwordError.innerHTML = res.data.errors.password;
        } else {
          window.location = "/";
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

和 Reactjs。后端与邮递员配合得很好,但是当我尝试从前端登录时,在 console.log 中我收到错误消息“cors 问题”... 我错过了什么? 这是错误信息: 从源“http://localhost:3000”访问“http://localhost:5000/api/user/login”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:当请求的凭据模式为“包含”时,响应中“Access-Control-Allow-Origin”标头的值不能是通配符“*”。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

这是提交后运行的函数的代码

【问题讨论】:

标签: node.js reactjs mongodb express


【解决方案1】:
  • 在前端应用的 package.json 中添加 Proxy。
 "proxy": "http://localhost:5000"
  • 在 axios 调用中,下一步而不是完整的 uri,只需将其称为
axios.post('/user/login')...
  • 现在在后端(节点)目录中使用 npm 添加以下依赖项
npm install cors
  • 现在在主服务器文件中使用它,即 server.js,如下所示
const cors = require('cors')
app.use(cors())

【讨论】:

  • 我刚试过,还不行。顺便说一句,cors 已经在 server.js 中安装和配置了
  • @MUHESI 您能否发布其他详细信息,即您在 api 的网络选项卡中得到什么响应?
猜你喜欢
  • 1970-01-01
  • 2018-02-18
  • 2018-05-16
  • 1970-01-01
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 2022-10-06
相关资源
最近更新 更多