beN*_*erd 3 node.js express backbone.js
我的 server.js 中有这个
app.post("/leadAPI/ed",function(request,response){
//api post code here
});
Run Code Online (Sandbox Code Playgroud)
在此发布请求中,我需要将包含在请求正文中的数据发布到具有特定 URL 的某些外部 API,并使用 response.send 将响应发回。如何以干净的方式做到这一点。在 expressjs 中有什么内置的吗?
正如 Andreas 所说,这不是 express 的职责。它的职责是在收到 HTTP 请求时调用您的函数。
您可以使用 node 的内置 HTTP 客户端,正如 Andreas 在评论中提到的那样,向您的外部站点发出请求。
尝试这样的事情:
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();
});
Run Code Online (Sandbox Code Playgroud)
我确定您需要对其进行调整以处理分块响应并弄清楚传输编码,但这就是您需要的要点。
有关详细信息,请参阅
http://nodejs.org/api/http.html
我会为此使用 Mikeal Rogers 的请求库:
var request = require('request');
app.post("/leadAPI/ed",function(req, res){
var remote = request('remote url');
req.pipe(remote);
remote.pipe(res);
});
Run Code Online (Sandbox Code Playgroud)