如何使用node-http-proxy进行302重定向?

时间:2014-10-11 19:15:50

标签: node.js http http-proxy node-http-proxy

我的代码:

var path = require('path');
var util = require('util');
var http = require('http');
var fs = require('fs');
var httpProxy = require('http-proxy');


httpProxy.createProxyServer({
    target: 'http://localhost:9000',
    agent: https.globalAgent,
    headers: {
        host: 'localhost'
    }
})
.listen(8000);

util.puts('proxy server listening on port 8000');

http.createServer(function targetServer(req, res) {
    res.writeHead(302, { 'Location': '/' }); //Here is the 302
    util.puts('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));

    res.end();

})
.listen(9000);

util.puts('target server listening on port 9000');

当我从浏览器发出请求时,我收到以下错误:

Error: socket hang up

我不知道这个错误意味着什么。任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

我确实让它发挥作用 我不得不做两件事:

  1. 包含follow-redirects包(npm install follow-redirects) 并改变我的http初始化: 要:
    var http = require('follow-redirects')。http; 从: var http = require('http');
  2. 在CreateProxyServer中包含 {changeOrigin:true} 属性: var proxy = httpProxy.createProxyServer({changeOrigin:true,toProxy:true,});
相关问题