如何在快递中使用Session in post方法

时间:2019-08-02 03:16:18

标签: node.js reactjs express axios

我将ExpressJS用作后端,而将Reactjs用作前端。我正在尝试在app.post中使用会话,但是当我不包含凭据时,无论何时设置凭据,即使设置了所有标头后,我都会收到以下错误,但它不起作用。 (注意:数据位于json中)

前端:

Axios.post('http://localhost:5002/api/me/create', data ,
            {
                withCredentials: true,
                headers: { 'content-type': 'application/json' },
            })

后端:

 app.post('/api/me/create', function (req, res) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:5000');
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    res.setHeader('Access-Control-Allow-Headers', 'content-type');
    res.setHeader('Content-Type', 'application/json');
    console.log(req.session.uuid);
    req.session.uuid = 5;
}

错误:

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.

1 个答案:

答案 0 :(得分:1)

问题

您违反了相同来源政策 –它说每个AJAX请求都必须与网站的确切主机,协议和端口相匹配。

可以看出,您的前端在端口5002上运行,而后端在端口5000上运行。因此浏览器会自动说:hmmm,这听起来像是一种威胁!和tadaa ... 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

您可以详细阅读here ...