Node.js 如何在express中使用Session in post方法
我使用ExpressJS作为后端,使用Reactjs作为前端。我正在尝试使用app.post中的会话,但当我不包含凭据时,它不起作用。每当我包含凭据时,即使在设置所有标题后,我仍会收到以下错误。(注:数据为json格式) 前端: 后端: 错误:Node.js 如何在express中使用Session in post方法,node.js,reactjs,express,axios,Node.js,Reactjs,Express,Axios,我使用ExpressJS作为后端,使用Reactjs作为前端。我正在尝试使用app.post中的会话,但当我不包含凭据时,它不起作用。每当我包含凭据时,即使在设置所有标题后,我仍会收到以下错误。(注:数据为json格式) 前端: 后端: 错误: Access to XMLHttpRequest at 'http://localhost:5002/api/me/create' from origin 'http://localhost:5000' has been blocked by CORS
Access to XMLHttpRequest at 'http://localhost:5002/api/me/create' from origin 'http://localhost:5000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
问题 您已经违反了同源策略——它规定每个AJAX请求必须与站点的确切主机、协议和端口匹配 可以看到,您的前端在端口5002上运行,后端在端口5000上运行。所以浏览器会自动显示:嗯,听起来像是威胁!还有塔达。。。CORS错误 要明确的是,这不是React错误。它同样影响所有的网络应用 如何修复它 1个CORS收割台 您可以通过运行以下命令安装
CORS
npm install cors
并将其用作如下的中间件:
var express = require('express');
// Import the library:
var cors = require('cors');
var app = express();
// Then use it before your routes are set up:
app.use(cors());
2代理服务器
如果无法修改服务器,则可以运行自己的代理。如果该代理与您的页面不在同一原点,则它可以返回Access Control Allow Origin标头
3 JSONP
如果CORS和代理服务器不适合您,JSONP可能会有所帮助。实际上,您使用回调参数发出GET请求:
(get) http://api.example.com/endpoint?callback=foo
您可以阅读详细信息…飞行前CORS错误意味着您的服务器上需要一个请求处理程序来处理选项请求并从中返回正确的信息,以便批准此类请求。请求的某些特征可能会触发预处理的需要(例如自定义头)。查看“飞行前CORS express”中的编码示例。
var express = require('express');
// Import the library:
var cors = require('cors');
var app = express();
// Then use it before your routes are set up:
app.use(cors());
(get) http://api.example.com/endpoint?callback=foo