我有nodejs应用程序处理用户的请求并接收我想代理内部API服务的cookie。如何通过使用node-fetch来解决这个问题?
请不要提供superagent。
我有nodejs应用程序处理用户的请求并接收我想代理内部API服务的cookie。如何通过使用node-fetch来解决这个问题?
请不要提供superagent。
您应该能够通过在请求的标头中设置cookie来传递cookie:
const opts = {
headers: {
cookie: 'accessToken=1234abc; userId=1234'
}
};
const result = await fetch(`/some/url`, opts);
简单来说,您可以编写一个中间件,其中包含对global.fetch的cookie,如下所示。
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;
您不需要node-featch,您可以从请求标题“Cookie”中读取用户cookie。看到 https://nodejs.org/dist/latest-v5.x/docs/api/http.html#http_message_headers
但是,如果使用跨域请求,则必须使用withCredential配置客户端请求并在服务器上添加CORS标头。看到这个: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
您应该能够通过在请求的标头中设置cookie来传递cookie:
const opts = {
headers: {
cookie: 'accessToken=1234abc; userId=1234'
}
};
const result = await fetch(`/some/url`, opts);
简单来说,您可以编写一个中间件,其中包含对global.fetch的cookie,如下所示。
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;
您不需要node-featch,您可以从请求标题“Cookie”中读取用户cookie。看到 https://nodejs.org/dist/latest-v5.x/docs/api/http.html#http_message_headers
但是,如果使用跨域请求,则必须使用withCredential配置客户端请求并在服务器上添加CORS标头。看到这个: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS