难以在 JavaScript 中通过提取请求发送 cookie

Difficulty sending cookies with fetch requests in JavaScript

我有两个独立的服务,一个 React 单页应用程序和一个 express API,我正在尝试从 SPA 到 API 使用新的 fetch 功能。由于这两个服务位于不同的域,我在 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

有人对如何解决这个问题有建议吗?任何帮助将不胜感激!

在撰写本文时,您使用的 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