node.js - 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
}
解决方案
我认为这只是一个开发问题,因为您的 express 实例和 reactjs 前端服务器在不同的端口上运行。在生产环境中,情况可能并非如此。
不要在您的开发周期中使用 CORS,而是尝试将请求从您的前端服务器代理到您的快速服务器。
例如,webpack devserver 有一个单独的代理配置https://webpack.js.org/configuration/dev-server/#devserver-proxy
推荐阅读
- laravel - Laravel-echo-server , net::ERR_CONNECTION_TIMED_OUT
- node.js - 模型在发布路由中返回未定义的属性但没有获取路由
- django - 选择多列与一列的group by django orm
- vb.net - DataGridView 中的算术运算
- postgresql - 定义表中不存在时删除 jsonb 键
- android - 如何在 FLEXIBLE 应用内更新 android 中完成下载时收到通知?
- r - 在 Shiny 的 Plotly 子图中未触发点击事件
- java - 每次开始新活动时都会覆盖 ArrayList 共享首选项
- ionic3 - IonScroll.scrollTop 不滚动
- matplotlib - Matplotlib:保存图表无法正常工作,除非我在它之后使用 plt.show()