代理与nodejs [英] Proxy with nodejs

查看:126
本文介绍了代理与nodejs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个webapp,对api。由于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
});

});

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

 发生错误:{stack:错误:ENOTFOUND,域名称未找到\在IOWatcher.callback(dns.js:74:15),消息:ENOTFOUND,未找到域名,errno:4,代码:ENOTFOUND} 


解决方案

看看 。它有一个如何调用 proxyRequest 的示例:

  proxy.proxyRequest (req,res,{
host:'localhost',
port:9000
});

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


I develop an webapp, against an api. As the api is not running on my local system, I need to proxy the request so I dont run in cross domain issues. Is there an easy way to do this so my index.html will send from local and all other GET, POST, PUT, DELETE request go to xyz.net/apiEndPoint.

Edit:

this is my first solution but didnt work

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
    });

});

It will serve the index, js, css files but dont route the rest to the external api. This is the error message I've got:

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"}

解决方案

Take a look at the readme for http-proxy. It has an example of how to call proxyRequest:

proxy.proxyRequest(req, res, {
  host: 'localhost',
  port: 9000
});

Based on the error message, it sounds like you're passing a bogus domain name into the proxyRequest method.

这篇关于代理与nodejs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆