0

我正在开发一个 Web 应用程序并使用 Google Chrome 60.0.3112.113 对其进行测试。

为了简化开发过程,我使用带有http-proxy-middleware的 node.js 开发 Web 服务器将我的 API 请求代理到后端。

现在,当我使用axios向 API 端点之一发送 HTTP POST 请求以在我的后端创建会话时,我得到稍微改变的响应标头(从 DevTools 复制):

直接响应
HTTP/1.1 200 OK
Content-Length: 122
Content-Type: application/json
Set-Cookie: sessionid={4621f755-37da-41da-bdbd-9a6ce0ee02b7}; Max-Age=31536000; Version=1
代理响应
HTTP/1.1 200 OK
X-Powered-By: Express
connection: close
content-length: 122
content-type: application/json
set-cookie: sessionid={4621f755-37da-41da-bdbd-9a6ce0ee02b7}; Max-Age=31536000; Version=1
Date: Thu, 07 Sep 2017 11:06:43 GMT

问题是 chrome 没有设置代理响应中指定的 cookie(DevTools->Application->Storage->Cookies 保持为空),但是直接响应按预期设置了 cookie。

Cookie 在 DevTools->Network-> My Request ->Cookies 中正确显示。两个版本(直接和代理)都通过http://localhost:[8080 / 3000]

set-cookiechrome中可以忽略小写标题吗?或者其他标题是否会干扰 cookie 的设置?

顺便说一句:在 Safari 10.1.2 (12603.3.8) 中运行良好

4

2 回答 2

0
// proxy middleware options 
var options = {
    target: 'http://localhost:8081', // target host 
    changeOrigin: true,               // needed for virtual hosted sites 
    ws: true,                         // proxy websockets 
    logLevel: "debug",
    pathRewrite: {
        '^/src/api/' : '/api/'
    },
    onProxyRes: function (proxyRes, req, res) {
        if (proxyRes.headers['set-cookie'] != undefined) {
            req.session['cookie'] = proxyRes.headers['set-cookie'];  // must be or you will get new session for each call
            req.session['proxy-cookie'] = proxyRes.headers['set-cookie'];  // add to other key because cookie will be lost
        }
        console.log("response: " + req.session.id);
        console.log(req.session);
    },
    onProxyReq: function (proxyReq, req, res) {
        // check for whether the session be freshed
        if (req.session.view)
            req.session.view ++;
        else
            req.session.view = 1;

        // use ower key to restore cookie
        if (req.session['proxy-cookie'] != undefined)
            proxyReq.setHeader('cookie', req.session['proxy-cookie'][0]);

        console.log("request: " + req.session.id);
        console.log(req.session);
    }
};
于 2017-12-07T03:23:19.750 回答
0

cookieDomainRewrite: 'localhost'

于 2021-04-19T08:39:56.230 回答