How to send cookies with node-fetch?

和自甴很熟 提交于 2020-01-10 17:26:26

问题


I've got nodejs application which handles user's requests and receives cookies which i want to proxy to internal API service. How to approach this by using node-fetch?

Don't offer superagent please.


回答1:


You should be able to pass along cookies by setting it in the header of your request:

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



回答2:


Read & write cookies like a bot

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)

For some reason the resulting cookies of node-fetch requests are not compatible with new requests, but we can parse them like this:

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:

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



回答3:


For simple, you can write a middleware which will include the cookies to global.fetch, like below.

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;



回答4:


You don't need node-featch, you can read users cookie from request header "Cookie". See 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. See this: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS



来源:https://stackoverflow.com/questions/34815845/how-to-send-cookies-with-node-fetch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!