http-proxy一直返回404

时间:2014-06-28 10:01:01

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

我尝试使用http-proxy代理对REST API的调用,但它会不断返回404代码。

这是对我的API的示例调用:http://petrpavlik.apiary-mock.com/notes它返回一些JSON数据。

这就是我的服务器代码:

var httpProxy = require('http-proxy');

var proxy = httpProxy.createServer({
  target:'http://petrpavlik.apiary-mock.com'
});

proxy.listen(8005);

proxy.on('error', function (err, req, res) {
  res.writeHead(500, {
    'Content-Type': 'text/plain'
  });

  res.end('Something went wrong. And we are reporting a custom error message.');
});

proxy.on('proxyRes', function (res) {
  console.log('RAW Response from the target', JSON.stringify(res.headers, true, 2));
});

当我尝试使用我的代理调用相同的请求时,这就是我得到的。

Petrs-MacBook-Air-2:~ petr$ curl -v 127.0.0.1:8005/notes
* About to connect() to 127.0.0.1 port 8005 (#0)
*   Trying 127.0.0.1...
* Adding handle: conn: 0x7f977280fe00
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7f977280fe00) send_pipe: 1, recv_pipe: 0
* Connected to 127.0.0.1 (127.0.0.1) port 8005 (#0)
> GET /notes HTTP/1.1
> User-Agent: curl/7.30.0
> Host: 127.0.0.1:8005
> Accept: */*
> 
< HTTP/1.1 404 Not Found
< cache-control: no-cache, no-store
< content-type: text/html; charset=utf-8
< date: Sat, 28 Jun 2014 09:40:29 GMT
* Server MochiWeb/1.0 (Any of you quaids got a smint?) is not blacklisted
< server: MochiWeb/1.0 (Any of you quaids got a smint?)
< content-length: 2960
< connection: Close
< 

我必须遗漏一些显而易见的东西,但我真的坚持这个。

2 个答案:

答案 0 :(得分:9)

如果您尝试代理Apiary Mock API,我已经这样做了:

var apiProxy = httpProxy.createProxyServer();
server.get("/api/v1", function (req, res) {
  delete req.headers.host;
  req.url = req.url.replace('/api/v1', '/');
  apiProxy.web(req, res, { target: 'http://private-XXXX.apiary-mock.com/' });
});

现在,在我的本地应用中,我请求GET /api/v1/notes代理http://private-XXXX.apiary-mock.com/notes

确保delete req.headers.host,否则目标服务器将匹配错误的主机。

答案 1 :(得分:3)

我偶然发现了同样的问题,但解决方案对我不起作用。最终这解决了我的404错误:

var proxyOptions = {
    ignorePath: true 
};

var apiProxy = httpProxy.createProxyServer(proxyOptions);