我试图将所有/ api /请求从本地节点服务器代理到远程服务器,同时向它们嵌入一些身份验证参数。
我目前的方法似乎适用于使用查询参数和POST的GET,只要我不提供"表格"请求库的参数,但是一旦我包含它,服务器就会开始抛出错误:写完后。
var express = require("express");
var request = require("request");
var parser = require("body-parser");
var strftime = require("strftime");
var app = express();
var path = require("path");
var port = 80;
var apiUrl = "http://example.com/";
var apiUser = "example";
var apiPass = "example";
app.use(express.static(path.join(__dirname, "/dist")));
app.use(parser.json());
app.use(parser.urlencoded({extended: true}));
app.get("/api/*/", function(req, res) {
console.log((strftime("%H:%M:%S") + " | GET -> " + req.url));
var url = apiUrl + req.url;
req.pipe(request.get(url, {
auth: {
user: apiUser,
pass: apiPass
}
})).pipe(res);
});
app.post("/api/*/", function(req, res) {
console.log((strftime("%H:%M:%S") + " | POST -> " + req.url));
var url = apiUrl + req.url;
req.pipe(request.post(url, {
form: req.body, // <----- RESULTS IN "write after end" error
auth: {
user: apiUser,
pass: apiPass
}
})).pipe(res);
});
app.listen(port);
console.log("Development server started, listening to localhost:" + port);
console.log("Proxying /api/* -> " + apiUrl + "/api/*");
这可能与身体解析器中间件有关,但我无法找到解决此问题的任何方法,而且我不太明白为什么&#34;形式:req.body&#34 ;会破坏剧本。记录req.body似乎输出了预期的参数。
我还尝试使用.form(req.body)替代链接语法,但结果是一样的。
答案 0 :(得分:3)
This is a couple of months old so the OP has probably moved on but I just ran into this and thought I'd post my solution for future searchers. The problem is that request writer is being ended when the reader ends and therefore the body cannot be written (and throws the 'write after end'). So we need to tell it not to end. When passing a body, you need to add { end : false } to the pipe options. For example:
app.post("/api/*/", function(req, res) {
console.log((strftime("%H:%M:%S") + " | POST -> " + req.url));
var url = apiUrl + req.url;
req.pipe(request.post(url, {
form: req.body,
auth: {
user: apiUser,
pass: apiPass
}
}), { end : false }).pipe(res);
});