使用nodejs的代理

And*_*rle 9 proxy node.js express

我开发了一个针对api的webapp.由于api没有在我的本地系统上运行,我需要代理请求,所以我不会在跨域问题上运行.有没有一种简单的方法可以做到这一点,所以我的index.html将从本地和所有其他GET,POST,PUT,DELETE请求发送到xyz.net/apiEndPoint.

编辑:

这是我的第一个解决方案,但没有奏效

var express = require('express'),
    app = express.createServer(),
    httpProxy = require('http-proxy');


app.use(express.bodyParser());
app.listen(process.env.PORT || 1235);

var proxy = new httpProxy.RoutingProxy();

app.get('/', function(req, res) {
    res.sendfile(__dirname + '/index.html');
});
app.get('/js/*', function(req, res) {
    res.sendfile(__dirname + req.url);
});
app.get('/css/*', function(req, res) {
    res.sendfile(__dirname + req.url);
});

app.all('/*', function(req, res) {
    proxy.proxyRequest(req, res, {
        host: 'http://apiUrl',
        port: 80
    });

});
Run Code Online (Sandbox Code Playgroud)

它将提供索引,js,css文件,但不将其余路由到外部api.这是我收到的错误消息:

An error has occurred: {"stack":"Error: ENOTFOUND, Domain name not found\n    at IOWatcher.callback (dns.js:74:15)","message":"ENOTFOUND, Domain name not found","errno":4,"code":"ENOTFOUND"}
Run Code Online (Sandbox Code Playgroud)

Dan*_*ile 5

看一下自述文件http-proxy.它有一个如何调用的示例proxyRequest:

proxy.proxyRequest(req, res, {
  host: 'localhost',
  port: 9000
});
Run Code Online (Sandbox Code Playgroud)

根据错误消息,听起来好像是在将伪造的域名传递给proxyRequest方法.