首页 > 解决方案 > Express.js API 无法从前端接收 cookie

问题描述

在 React.js 应用程序中,我使用该js-cookie库设置 2 个 cookie。我能够将 cookie 记录到控制台。我还在 chrome 扩展中看到了两个 cookie,并且键/值匹配。

我通过一个获取请求发送 cookie,该请求有一个密钥credentials: 'include'

async function requestAllAccountData() {
  const allAccountDataEndpoint = buildUrl(REACT_APP_HTTPS_BACKEND_DOMAIN, {
    path: '/account-data/all'
  });

  console.log('allAccountDataEndpoint', allAccountDataEndpoint);

  try {
    const response = await fetch(allAccountDataEndpoint, {
      method: 'get',
      mode: 'cors',
      credentials: 'include', // for cookie passage to back end
      headers: {
        'content-type': 'application/json',
      },
    });

    const allAccountData = await response.json();
    console.log('allAccountData',allAccountData);
    return allAccountData;
  } catch (error) {
    throw new Error(error);
  }
}

具有以下代码的 express 端点无法打印 cookie 值。稍后在代码中缺少 cookie 键/值将控制发送到一条悲伤的道路。

router.get('/all', async (req: Request, res: Response) => {
  console.log('req.cookies', req.cookies); 
  // [Object: null prototype] {}

  console.log('number of cookies keys', Object.keys(req.cookies).length);
  // 0

在 server.ts 中,我将cookie-parser包作为调用的中间件引入:

const corsConfigured = cors({
  credentials: true, // this setting should accept cookies
  origin: true,
});

server
  .use(corsConfigured)
  .use(cookieParser())
  .use(Express.json())
  .use('/account-data', accountDataRouter);
  // ^ this is the router shown in the prior code sample

我没有做些什么来导致 cookie 在路由处理程序中不可见?

cookie 没有设置特殊选项。

更新:请求信息

在 Google Chrome 中,我在 GET 或 OPTIONS 请求中都看不到 cookie 的标头:

Request Method: GET
Status Code: 401 
Remote Address: [2600:1f16:d83:1201::6e:1]:443
Referrer Policy: strict-origin-when-cross-origin
access-control-allow-credentials: true
access-control-allow-origin: http://localhost:3000
content-length: 33
content-type: application/json; charset=utf-8
date: Thu, 01 Oct 2020 16:05:30 GMT
etag: W/"21-EAAxQ8w9ulq766ONDoxsOSjUMSY"
status: 401
vary: Origin
x-powered-by: Express
:authority: asanarepeater.ngrok.io
:method: GET
:path: /account-data/all
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9,th;q=0.8
content-type: application/json
origin: http://localhost:3000
referer: http://localhost:3000/
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36

.

Request Method: OPTIONS
Status Code: 204 
Remote Address: [2600:1f16:d83:1201::6e:1]:443
Referrer Policy: strict-origin-when-cross-origin
access-control-allow-credentials: true
access-control-allow-headers: content-type
access-control-allow-methods: GET,HEAD,PUT,PATCH,POST,DELETE
access-control-allow-origin: http://localhost:3000
content-length: 0
date: Thu, 01 Oct 2020 16:05:28 GMT
status: 204
vary: Origin, Access-Control-Request-Headers
x-powered-by: Express
:authority: asanarepeater.ngrok.io
:method: OPTIONS
:path: /account-data/all
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9,th;q=0.8
access-control-request-headers: content-type
access-control-request-method: GET
origin: http://localhost:3000
referer: http://localhost:3000/
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36

标签: node.jsexpresscookies

解决方案


推荐阅读