简体   繁体   English

如何使用 node-fetch 发送 cookie?

[英]How to send cookies with node-fetch?

I've got nodejs application which handles user's requests and receives cookies which i want to proxy to internal API service.我有 nodejs 应用程序,它处理用户的请求并接收我想代理到内部 API 服务的 cookie。 How to approach this by using node-fetch?如何使用节点获取来解决这个问题?

Don't offer superagent please.请不要提供超级代理。

You should be able to pass along cookies by setting it in the header of your request:您应该能够通过在请求标头中设置来传递 cookie:

const opts = {
    headers: {
        cookie: 'accessToken=1234abc; userId=1234'
    }
};
const result = await fetch(`/some/url`, opts);

Read & write cookies like a bot像机器人一样读写 cookie

async function login() {
  return fetch('<some_url>/login', {
      'headers': {
          'accept': '*/*',
          'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
          'cookie': '',
      },
      'body': 'username=foo&password=bar',
      'method': 'POST',
  });
}

(async() => {
  const loginResponse = await login();
  const loginCookies = parseCookies(loginResponse);
})();

You may want to include: accept-language , user-agent , referer , accept-encoding , etc. (check a sample request on your Chrome DevTools via the Network tab)您可能希望包括: accept-languageuser-agentrefereraccept-encoding等(通过“网络”选项卡检查 Chrome DevTools 上的示例请求)

For some reason the resulting cookies of node-fetch requests are not compatible with new requests, but we can parse them like this:由于某些原因,节点获取请求生成的 cookie 与新请求不兼容,但我们可以像这样解析它们:

function parseCookies(response) {
  const raw = response.headers.raw()['set-cookie'];
  return raw.map((entry) => {
    const parts = entry.split(';');
    const cookiePart = parts[0];
    return cookiePart;
  }).join(';');
}

Pass cookies in your future requests through the same headers:通过相同的标头在您未来的请求中传递 cookie:

  return fetch('<some_url>/dashboard', {
    'headers': {
        'accept': '*/*',
        'cookie': parsedCookies,
    },
    'method': 'GET',
  });

For simple, you can write a middleware which will include the cookies to global.fetch, like below.为简单起见,您可以编写一个中间件,将 cookie 包含到 global.fetch,如下所示。

const realFetch = fetch;

function cookieFetch(fetch, cookie) {
  return (url, opts) => {
    opts = opts || {};
    return fetch(url, Object.assign(opts, {
      headers: Object.assign(opts.headers || {}, { cookie })
    }));
  };
}

function middleware(req, res, next) {
  const kuki = req.headers.cookie;
  global.fetch = kuki ?
    cookieFetch(realFetch, kuki) :
    realFetch;
  next();
}

module.exports = middleware;

You don't need node-featch, you can read users cookie from request header "Cookie". 您不需要node-featch,您可以从请求标题“Cookie”中读取用户cookie。 See https://nodejs.org/dist/latest-v5.x/docs/api/http.html#http_message_headers 请参阅https://nodejs.org/dist/latest-v5.x/docs/api/http.html#http_message_headers

But if you use the cross-domain request, you must configured your client request with withCredential and add CORS-headers on server. 但是,如果使用跨域请求,则必须使用withCredential配置客户端请求并在服务器上添加CORS标头。 See this: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS 请参阅: https//developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM