mcheli
mcheli

Reputation: 35

Performing POST Request in Separate Node Module with Express

I'm building a web application that processes a post request then performs a POST request to another server, and then redirects the user based on the returned information.

End result is user types in their username and clicks submit --> application process the post, takes the username --> application performs post to external server including the username --> server returns the url of the server the user should be on --> application redirects the user to that application.

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

The problem is with returning the information from the external post module to the server.js module so that it can perform the redirect. Currently I have the variable uUrl (which is correctly populated with the URL from the post) returned from the function. However the findUserInstance module returns null.

How can I get the value of uUrl from the findUserInstance module to the server.js module?

Upvotes: 0

Views: 102

Answers (2)

Jules Goullee
Jules Goullee

Reputation: 591

Yes now uurl in server.js is asynchronous change handler:

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

  });

});

Upvotes: 0

Jules Goullee
Jules Goullee

Reputation: 591

@bryan euton good response you should return any object in findUserInstance like promise! 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();

  });

}

Upvotes: 1

Related Questions