How to send cookies using node-fetch?

I have a nodejs application that processes user requests and receives cookies that I want a proxy server for an internal API service. How to approach this with node-fetch?

Do not offer a superagent.

+13
javascript fetch
source share
4 answers

You should be able to send 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); 
+23
source share

For simplicity, you can write middleware that will include cookies in global.fetch, as shown 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; 
0
source share

Read and 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 can include: accept-language , user-agent , referer , accept-encoding , etc. (Check out the Chrome DevTools request example)

For some reason, the resulting site selection request cookies are not compatible with new requests, but we can analyze them as follows:

 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', }); 
0
source share

You don’t need node-featch, you can read the user cookie from the cookie request header. See https://nodejs.org/dist/latest-v5.x/docs/api/http.html#http_message_headers

But if you are using a cross-domain request, you must configure your client request using Credential and add the CORS headers on the server. See this: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

-4
source share

All Articles