没有回应使用快速代理路由 [英] No response using express proxy route

查看:93
本文介绍了没有回应使用快速代理路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用nodejs,express和htt-proxy写了一个小代理。它适用于服务本地文件,但在代理到外部api时失败:

  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){
req.url ='v1 / public / yql?q = show%20tables& format = json& callback =';
proxy.proxyRequest(req,res,{
host:'query.yahooapis.com',// yahoo只是一个例子来验证它不是apis错误
端口: 8080
});

});

问题是,没有来自yahoo api的回复,也许有一个回应,但我不

解决方案

更简单的 pipe code>请求 -Package

  var request = require('request'); 

app.use('/ api',function(req,res){
var url = apiUrl + req.url;
req.pipe(request(url)) .pipe(res);
});

它将整个请求管道传递给API,并将响应管道传回给请求者。这也处理POST / PUT / DELETE和所有其他请求\o /



如果你也关心查询字符串,你应该管道它

  req.pipe(request({qs:req.query,uri:url}))。pipe(res); 


I've written a small proxy with nodejs, express and htt-proxy. It works well for serving local files but fails when it comes to proxy to external api:

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) {
    req.url = 'v1/public/yql?q=show%20tables&format=json&callback=';
    proxy.proxyRequest(req, res, {
        host: 'query.yahooapis.com', //yahoo is just an example to verify its not the apis fault
        port: 8080
    });

});

The problem is that there is no response from the yahoo api, maybe there is an response but i dont came up in the browser.

解决方案

Even simpler with pipe and request-Package

var request = require('request');

app.use('/api', function(req, res) {
  var url = apiUrl + req.url;
  req.pipe(request(url)).pipe(res);
});

It pipes the whole request to the API and pipes the response back to the requestor. This also handles POST/PUT/DELETE and all other requests \o/

If you also care about query string you should pipe it as well

req.pipe(request({ qs:req.query, uri: url })).pipe(res);

这篇关于没有回应使用快速代理路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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