Node.js 如何向节点http代理响应添加头
我需要在第三方服务上解决CORS问题,所以我想构建一个代理来添加标题“Access Control Allow Origin:*” 为什么这段代码没有添加标题Node.js 如何向节点http代理响应添加头,node.js,http,https,Node.js,Http,Https,我需要在第三方服务上解决CORS问题,所以我想构建一个代理来添加标题“Access Control Allow Origin:*” 为什么这段代码没有添加标题 httpProxy = require('http-proxy'); var URL = 'https://third_party_server...'; httpProxy.createServer({ secure: false, target: URL }, function (req, res, proxy) { res
httpProxy = require('http-proxy');
var URL = 'https://third_party_server...';
httpProxy.createServer({ secure: false, target: URL }, function (req, res, proxy) {
res.oldWriteHead = res.writeHead;
res.writeHead = function(statusCode, headers) {
/* add logic to change headers here */
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
res.oldWriteHead(statusCode, headers);
}
proxy.proxyRequest(req, res, { secure: false, target: URL });
}).listen(8000);
您有可用的
proxyRes
事件
因此,类似的方法应该有效:
proxy.on('proxyRes', function(proxyRes, req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
});
完整的工作示例(好吧,当我说完整时,我并不是说这是一个安全的故障保护真实代理,但它可以解决您的问题):
尽管这个问题很老了,但这是谷歌的第一个结果,而目前的答案并没有提供太多信息 需要注意的第一点是,
proxyRes
没有setHeader()
方法。此外,如果您尝试使用res.setHeader('header-to-override','new value')
覆盖proxyRes
标题,它将不起作用(我假设是因为触发此事件后,标题从proxyRes
复制到res
)
似乎我们并不是唯一有这个问题的人:
以下是在我的情况下添加额外的缓存控制
头的解决方案:
proxy.on('proxyRes',函数(proxyRes,req,res){
if(代理标头['cache-control']){
代理标头['cache-control']+=',代理重新验证'
}否则{
proxyRes.headers['cache-control']=“代理重新验证”
}
})
尝试使用模块,npm install cors
因此,您必须在res
中设置标题(您可以在proxyRes
事件或proxyReq
事件中设置标题)。不在这些事件的proxyRes
或proxyReq
参数中。请注意,如果目标已设置访问控制允许原点,则此操作似乎不起作用,因为当代理写入res
时,您的自定义值将被覆盖。这会给出错误信息“已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:它没有HTTP ok状态。”。“这个答案是从2013年开始的,事情可能已经发生了一些变化。但我认为您这里的主要问题是,您的选项http query没有200 Ok响应,它没有http Ok status
,这是另一个问题。
var http = require('http'),
httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});
var server = http.createServer(function(req, res) {
proxy.web(req, res, {
target: 'https://third_party_server...',
secure: false,
ws: false,
prependPath: false,
ignorePath: false,
});
});
console.log("listening on port 8000")
server.listen(8000);
// Listen for the `error` event on `proxy`.
// as we will generate a big bunch of errors
proxy.on('error', function (err, req, res) {
console.log(err)
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end("Oops");
});
proxy.on('proxyRes', function(proxyRes, req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
});