如何发送cookie与节点获取?

我有nodejs应用程序,它处理用户的请求,并接收我想代理内部API服务的cookie。 如何通过使用节点获取?

请不要提供superagent。

您应该可以通过在您的请求的标题中设置cookie来传递Cookie。

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

你不需要node-featch,你可以从请求头“Cookie”中读取用户的cookie。 请参阅https://nodejs.org/dist/latest-v5.x/docs/api/http.html#http_message_headers

但是,如果您使用跨域请求,则必须使用withCredentialconfiguration您的客户端请求,并在服务器上添加CORS头。 看到这个: https : //developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

简单来说,你可以写一个中间件,将cookies包含到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;