发布与expressjs远程URL

问题描述 投票:1回答:3

我有这个在我的server.js

app.post("/leadAPI/ed",function(request,response){
//api post code here
});

在这篇文章要求我需要张贴包含在请求体到一些外部API与特定的URL数据并发送回响应使用response.send。如何做一个干净的方式。有什么建在这expressjs?

node.js backbone.js express
3个回答
3
投票

作为安德烈亚斯提到的,这是无法表达的义务。其职责是当一个HTTP请求进入调用你的函数。

您可以使用节点内置的HTTP客户端,如安德烈亚斯在评论中也提到,对您的外部网站的请求。

尝试是这样的:

var http = require('http');

app.post("/leadAPI/ed", function(request, response) {
  var proxyRequest = http.request({
      host: 'remote.site.com',
      port: 80,
      method: 'POST',
      path: '/endpoint/url'
    },
    function (proxyResponse) {
      proxyResponse.on('data', function (chunk) {
        response.send(chunk);
      });
    });

  proxyRequest.write(response.body);
  proxyRequest.end();
});

我敢肯定,你需要去适应它来处理分块响应,并找出传输编码的,但是这是你所需要的要点。

有关详细信息,请参阅

http://nodejs.org/api/http.html


4
投票

我会用Mikeal罗杰斯request库这样的:

var request = require('request');

app.post("/leadAPI/ed",function(req, res){
  var remote = request('remote url');

  req.pipe(remote);
  remote.pipe(res);
});

1
投票

你可以不喜欢这样。

var request = require('request');
var url = "<remote url>"
app.post("/leadAPI/ed",function(request, response){
  request.get({url:url, headers:request.headers, body:request.body}, function (err, res, body) {
    if(!err) {
      response.status(200).send(res) // JSON.stringify(res) if res is in json
    }
  })
})

请记住,内容类型应该是两者相同。

© www.soinside.com 2019 - 2024. All rights reserved.