Nodejs 代理没有响应
我有一个提供静态文件(html、js、css)的node.js 应用程序。静态文件中,完成了一些ajax请求(请求中带有/TEST)。我需要将这些请求代理到在 localhost:213445 上运行的另一台服务器。静态页面正确显示,但当涉及代理请求时,它永远挂起......
我的代码是:
var express = require("express");
var httpProxy = require('http-proxy');
var fs = require('fs');
// Create https server
var app = express.createServer({
key: fs.readFileSync('privatekey.pem'),
cert: fs.readFileSync('certificate.pem')
});
// Handle static files
app.use(express.static(__dirname + '/public'));
// Proxy request
app.all('/TEST/*',function(req, res){
// Remove '/TEST' part from query string
req.url = '/' + req.url.split('/').slice(2).join('/');
// Create proxy
var proxy = new httpProxy.HttpProxy();
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 21345,
enableXForwarded: false,
buffer: proxy.buffer(req)
});
});
// Run application
app.listen(10443);
I have a node.js app that serve static files (html, js, css). Among the static files, some ajax request are done (with /TEST in the request). I need those request to be proxied to another server running on localhost:213445. The static pages are correctly displayed but when it comes to proxied request it hangs forever...
My code is:
var express = require("express");
var httpProxy = require('http-proxy');
var fs = require('fs');
// Create https server
var app = express.createServer({
key: fs.readFileSync('privatekey.pem'),
cert: fs.readFileSync('certificate.pem')
});
// Handle static files
app.use(express.static(__dirname + '/public'));
// Proxy request
app.all('/TEST/*',function(req, res){
// Remove '/TEST' part from query string
req.url = '/' + req.url.split('/').slice(2).join('/');
// Create proxy
var proxy = new httpProxy.HttpProxy();
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 21345,
enableXForwarded: false,
buffer: proxy.buffer(req)
});
});
// Run application
app.listen(10443);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我有同样的问题。如果您注释掉,
您将看到代理可以工作。
如果使用了express.static,不确定如何修复它
Marak Squires 回应了错误 报告!
I have the same issue. If you comment out the
you will see that the the proxy works.
Not sure how to fix it if express.static is used
Marak Squires responded to the bug report!
正如 http-proxy issue 180 中所述,该问题与上面提到的 connect 完成的非标准操作:
使用 npm 安装 connect-restreamer 并将其作为 Express 的 app.configuration 中的最后一项:
然后执行以下操作:
这将传递整个 URL,包括“/proxy/”到目标主机。您可以 重写/修改如果您想模仿来自特定 CNAME 虚拟主机或不同 URL 字符串的请求,请在进入
proxyRequest()
之前添加 req。As described on the http-proxy issue 180 the trouble is related to the non-standard things done by connect mentioned above:
Use npm to install connect-restreamer and make this the final item in your app.configuration of express:
Then do something like:
This will pass the whole URL, including "/proxy/" to the target host. You can rewrite/modify the headers of the req before they go into the
proxyRequest()
if you, e.g. want to mimic the request coming from a specific CNAME virtual host or different URL string.