如何将标头添加到node-http-proxy响应 [英] How to Add Headers to node-http-proxy Response
本文介绍了如何将标头添加到node-http-proxy响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在第三方服务上解决CORS,所以我想构建一个代理来添加标题Access-Control-Allow-Origin:*。
I need to solve CORS on a third party service, so I want to build a proxy to add the header "Access-Control-Allow-Origin: *".
为什么这段代码没有添加标题?
Why is this code is not adding the header?
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');
});
完整的工作示例(好吧,当我说完全时我并不是说这是一个安全 - 失败 - 真正的代理,但它可以解决你的问题):
Full working example (well, when I say full I do not mean this is a secure-failsafe-real proxy, but it does the job for your question):
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');
});
这篇关于如何将标头添加到node-http-proxy响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文