【问题标题】:React Axios Dispatching CORS policy errorReact Axios 调度 CORS 策略错误
【发布时间】:2021-04-19 14:24:33
【问题描述】:

我一直在开发一个 React 应用程序来通过 express 后端对用户进行身份验证。我已经通过使用邮递员发送 POST 请求来测试快递服务器,一切正常。

但我在使用 React 应用程序执行相同的 POST 请求时遇到了一个奇怪的错误。

我检查了请求负载,发送的 JSON 数据是正确的。

下面给出的是 axios 操作的代码 sn-p。

export const registerUser=(userData, history) => dispatch => {
    axios.post("http://localhost:5000/users/register",userData)
        .then( res => {
            console.log(res)
            history.push("/login") } )
}

非常感谢任何有关如何解决此问题的指示。

【问题讨论】:

标签: reactjs axios


【解决方案1】:

后端需要设置cors,先添加cors包,像这样使用

 const app = express();

 app.use(cors());

这将允许所有站点连接到您的后端,您可以对其进行限制,以便只有某些站点可以像这样使用它

app.use(
  cors({
    origin: "your app route",
  })
);

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 2020-12-18
    • 2021-02-22
    • 2021-08-14
    • 2022-06-22
    • 2021-10-13
    • 2019-10-01
    • 2021-11-14
    • 2020-07-26
    相关资源
    最近更新 更多