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

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

问题描述

我用 nodejs、express 和 htt-proxy 编写了一个小型代理.它适用于提供本地文件,但在代理到外部 api 时失败:

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

});

问题是 yahoo api 没有响应,也许有响应,但我没有在浏览器中出现.

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.

推荐答案

使用 piperequest-Package

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

它将整个请求通过管道传送到 API,并将响应通过管道返回给请求者.这也处理 POST/PUT/DELETE 和所有其他请求 o/

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天全站免登陆