我正在构建一个Web应用程序,用于处理发布请求,然后对另一个服务器执行POST请求,然后根据返回的信息重定向用户。使用Express在独立节点模块中执行POST请求
最终结果是用户在他们的用户名和点击提交 - >应用过程后,需要用户名 - >应用程序执行发布到外部服务器包括用户名 - >服务器返回服务器的用户的URL应该开启 - >应用程序将用户重定向到该应用程序。
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var findUser = require('./findUserInstance')
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile(__dirname + "/" + "index.htm");
})
app.post('/process_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
response = {
username:req.body.username
};
var uUrl = findUser.url(response.username);
console.log("redirecting to " + uUrl);
res.redirect(findUser.url(response.username));
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function() {
var host = server.address().address
var port = server.address().port
console.log("App listening at http://%s:%s", host, port)
})
findUserInstance.js
exports.url = function(uName) {
var http = require("https");
var uUrl;
var options = {
"method": "POST",
"hostname": "removed",
"port": null,
"path": "removed",
"headers": {
"appkey": "removed",
"content-type": "application/json",
"cache-control": "no-cache",
"Accept": "application/json",
"postman-token": "7d87bcf1-8e11-9717-2f6e-8150a5625acd"
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function() {
var body = Buffer.concat(chunks);
var jsoncontent = JSON.parse(body);
uUrl = jsoncontent.rows[0].url;
console.log("The following should be: user.instance.url.com)
console.log(jsoncontent.rows[0].url);
return uUrl; //The information that I want to return to server.js
});
});
req.write(JSON.stringify({username: uName}));
req.end();
}
问题是与从外部交模块中的信息返回到server.js模块,以便它可以执行重定向。目前,我有从函数返回的变量uUrl(正确填充了来自帖子的URL)。但是findUserInstance模块返回null。
如何从findUserInstance模块获取uUrl的值到server.js模块?
谢谢!这看起来不错,但我仍然遇到问题。现在url函数返回[object Object](没有值)。我需要修改server.js中的任何内容吗? – mcheli