我的本地开发脚本使用代理来绕过CORS(除其他外)。我首先得到一些错误的cookie,允许我在开发时跳过我的应用程序中的身份验证。然后回调到spoofCookies设置我的静态代理 - 它提供我所有的本地静态内容,然后为路由到/ microsvc的所有呼叫设置代理。我接听电话,注入我的欺骗性cookie,并将其转发到远程主机上的相同路径。
这个脚本非常适合GET,但我对如何编写POST部分感到困惑。 req永远不会显示我通过我的代理发送的POST表单,因此我必须做一些非常错误的事情。
感谢您的时间
/*jslint node:true white:true nomen:true es5:true*/
'use strict';
var PORT_HTTP = process.env.PORT || 4400;
var localAddress = "http://localhost:" + PORT_HTTP;
var apiAddress = { label: "On-site Ethernet Plug",
protocol: "http://",
port: 80,
host : "10.17.100.11",
microsvc: "/microsvc",
auth: "/login.form"
};
var https = require('https');
var path = require('path');
var express = require('express');
var app = express();
var spoofCookie = require('./utils/spoof-cookies');
var cookies = [];
var proxy = function(myPath, searchOptions, req, res, cookies) {
var options = {
hostname: apiAddress.host,
port: apiAddress.port,
path: apiAddress.microsvc + searchOptions,
rejectUnauthorized: false
};
if(cookies.length){
options.headers = {
"Cookie":cookies[0]
};
}
try {
console.log('FROM: ' + localAddress + myPath + searchOptions + '\n' +
'↳ TO: ' + apiAddress.protocol + apiAddress.host + apiAddress.microsvc + searchOptions);
options.method = req.method;
if(options.method == 'POST' || options.method == 'PUT') {
// HELP
// form data never appears in output
console.log(req);
} else {
var r = https.request(options, function(resX) {
resX.setEncoding('utf8');
var responseData = '';
resX.on('data', function(chunk) {
responseData += chunk;
});
resX.on('end', function() {
res.send(JSON.parse(responseData));
});
});
r.on('error', function(e) {
if (e.code == "ENOTFOUND") {
console.error("File not found on remote");
} else {
console.error('ff ' + e);
}
});
}
req.pipe(r).pipe(res);
} catch (e) {
console.error(e);
}
};
// START - first get spoofed cookies
spoofCookie.getCookies(apiAddress, function(cookies) {
// set up server
var httpServer = http.createServer(app);
httpServer.listen(PORT_HTTP);
// microservice proxy
app.use('/microsvc', function (req, res) {
proxy('/microsvc', req.url, req, res, cookies);
});
console.log("HTTP server started: " + localAddress);
});
// static server runs anything that isn't set up for proxy
app.use(express.static(path.resolve(path.join(__dirname, "..", "app"))));
答案 0 :(得分:1)
默认情况下快速is not parsing请求正文。
req.body
包含请求正文中提交的键值对数据。默认情况下,它是undefined
,并在您使用正文解析中间件(例如body-parser和multer)时填充。
因此,使用body-parser
的设置看起来就是这样。
首先,在声明路由之前将中间件附加到某处:
var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// microservice proxy
app.use('/microsvc', function (req, res) {
proxy('/microsvc', req.url, req, res, cookies);
});
然后,访问request.body
中的请求内容:
if(options.method == 'POST' || options.method == 'PUT') {
console.log(req.body);
}