首页 > 解决方案 > CORS 预检通道未成功,React to Express

问题描述

当通过 CORS 从我的 React 应用程序向我的 Node.JS 和 Express.js 后端发送请求时,我得到:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3001/students/login. (Reason: CORS preflight channel did not succeed).

我使用 axios 发送请求,这是请求配置:

({ email, password }) => {
        return axios.post(API_ENDPOINT + UCENIK.post.login,
            { email, password },
            {
                withCredentials: true,
                Headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                }
            })
    }

我尝试在 Express 中使用以下标头允许 CORS:

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", req.headers.origin);
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization')");
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
    next();
});

编辑:使用 npm Cors 模块修复并提供此对象进行设置:

{
    origin: 'http://localhost:3000',
    cors: true
}

标签: node.jsreactjsexpresscors

解决方案


我认为这只是一个开发问题,因为您的 express 实例和 reactjs 前端服务器在不同的端口上运行。在生产环境中,情况可能并非如此。

不要在您的开发周期中使用 CORS,而是尝试将请求从您的前端服务器代理到您的快速服务器。

例如,webpack devserver 有一个单独的代理配置https://webpack.js.org/configuration/dev-server/#devserver-proxy


推荐阅读