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

时间:2015-04-15 22:57:55

标签: javascript cookies express

我有两个单独的服务,一个React单页面应用程序和一个express API,我尝试使用新的fetch功能从SPA与API进行通信。由于这两项服务位于不同的域中,因此我在express应用程序中使用CORS中间件,以便从SPA向API发出请求。我试图让fetch个请求也包含Cookie,以便我可以验证我的express应用中的Cookie,例如

在客户端:

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

在服务器端:

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!' });
});

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

示例cookie:

name: token
value: TOKEN_VALUE
domain: localhost
path: /
http: false
secure: false

有没有人就如何处理此问题提出建议?任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:7)

您正在使用的fetch polyfill库不符合本文规范。对于凭据,它预计' cors'成为价值而不是'包括'。我会在第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