【问题标题】:Performing POST Request in Separate Node Module with Express使用 Express 在单独的节点模块中执行 POST 请求
【发布时间】:2023-04-03 20:00:01
【问题描述】:

我正在构建一个 Web 应用程序,它处理一个 post 请求,然后向另一个服务器执行一个 POST 请求,然后根据返回的信息重定向用户。

最终结果是用户输入他们的用户名并点击提交 --> 应用程序处理帖子,获取用户名 --> 应用程序执行包含用户名的外部服务器的帖子 --> 服务器返回用户应该使用的服务器的 url be on --> 应用程序将用户重定向到该应用程序。

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

问题在于将信息从外部 post 模块返回到 server.js 模块,以便它可以执行重定向。目前我有从函数返回的变量 uUrl (正确填充了帖子中的 URL)。但是 findUserInstance 模块返回 null。

如何从 findUserInstance 模块中获取 uUrl 的值到 server.js 模块中?

【问题讨论】:

    标签: javascript node.js rest post express


    【解决方案1】:

    @bryan euton 很好的回应,你应该像承诺一样返回 findUserInstance 中的任何对象! https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise

    exports.url = function(uName) {
      return new Promise( function (resolve, reject){
    
        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);
            resolve(uUrl); //The information resolve promise with your datas
          });
    
        });
    
        req.write(JSON.stringify({username: uName}));
        req.end();
    
      });
    
    }
    

    【讨论】:

    • 谢谢!这看起来很棒,但我仍然遇到问题。现在 url 函数返回 [object Object](无值)。我需要修改 server.js 中的任何内容吗?
    【解决方案2】:

    是的,现在 server.js 中的 uurl 是异步更改处理程序:

    app.post('/process_post', urlencodedParser, function (req, res) {
    
      // Prepare output in JSON format
      response = {
        username:req.body.username
      };
    
      findUser.url(response.username).then( function(uUrl){
    
        console.log("redirecting to " + uUrl);
        res.redirect(findUser.url(response.username));
        res.end(JSON.stringify(response));
    
      });
    
    });
    

    【讨论】:

    • 太棒了!工作完美。非常感谢你!
    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 2016-07-05
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多