难以使用JavaScript中的抓取请求发送Cookie

Jos*_*ack 10 javascript cookies express

我有两个单独的服务,一个React页面应用程序和一个expressAPI,我正在尝试使用新fetch功能从SPA进行通信.由于这两个服务位于不同的域,我在express应用程序内部使用CORS中间件,以便从SPA向API发出请求.我正在尝试使任何fetch请求也包括cookie,以便我可以验证我的express应用程序中的cookie ,例如

在客户端:

fetch('http://localhost:8000/hello', { 
    credentials: 'include', 
    mode: 'cors' 
}).then(/* ... */)
Run Code Online (Sandbox Code Playgroud)

在服务器端:

var app = express();

app.use(cors({ credentials: true });
app.use(cookieParser());

app.get('/hello', function (req, res) {
  // Try and find the cookies sent with the request
  console.log(req.cookies);

  res.status(200).json({ message: 'cookies received!' });
});
Run Code Online (Sandbox Code Playgroud)

但是,无论我尝试什么,我仍然无法访问request对象上的任何cookie,即使我可以通过使用访问它们document.cookies.

一个示例cookie:

name: token
value: TOKEN_VALUE
domain: localhost
path: /
http: false
secure: false
Run Code Online (Sandbox Code Playgroud)

有没有人有关于如何处理这个问题的建议?任何帮助将不胜感激!

Cor*_*dle 7

您正在使用的fetch polyfill库不符合本文的规范.对于凭证,它期望'cors'是值而不是'include'.我会在第264行编辑我的本地fetch.js副本以适应标准,提交拉取请求,并在寻找更好的支持的polyfill库.

请参阅未解决的问题:https://github.com/github/fetch/issues/109

https://github.com/github/fetch

https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch