gpt4 book ai didi

node.js - http-proxy 一直返回 404

转载 作者:搜寻专家 更新时间:2023-10-31 22:56:49 25 4
gpt4 key购买 nike

我正在尝试使用 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
<

我一定遗漏了一些明显的东西,但我真的坚持这一点。

最佳答案

如果您尝试代理 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

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

关于node.js - http-proxy 一直返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24465675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com