用expressjs发布到远程URL [英] posting to a remote url with expressjs

查看:51
本文介绍了用expressjs发布到远程URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的server.js中有这个

i have this in my server.js

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

在此发布请求中,我需要使用特定的URL将请求正文中包含的数据发布到某个外部API,然后使用response.send将响应发送回去.如何以一种干净的方式做到这一点.在expressjs中有什么内置功能吗?

In this post request i need to post data contained in request body to some external API with a specific URL and send the response back using response.send. How to do it in a clean fashion. Is there anything build in for this in expressjs?

推荐答案

正如安德里亚斯(Andreas)所说,这不是表达的责任.它的职责是在HTTP请求进入时调用您的函数.

As Andreas mentioned, this isn't express's duty. Its duty is to invoke your function when an HTTP request comes in.

您可以使用节点的内置HTTP客户端(如Andreas在评论中所述)来向您的外部站点发出请求.

You can use node's built-in HTTP client, as Andreas also mentioned in a comment, to make a request to your external site.

尝试这样的事情:

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

我确定您需要对其进行调整以处理分块的响应并弄清楚传输编码,但这就是您需要的要旨.

I'm sure you'll need to adapt it to handle chunked responses and figure out the transfer-encoding, but that is the gist of what you need.

有关详细信息,请参见

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

这篇关于用expressjs发布到远程URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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