最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting parameters of post request in node js - Stack Overflow

programmeradmin1浏览0评论

I am struggling since I am trying to retrieve all the parameters of a POST request in node.js, but it's not gonna work.

Here the post request from the webpage:

var email = $('#email').val();
          var name = $('#name').val();
          var surname = $('#surname').val();
          var role = $('#role').val();
          var telephone = $('#telephone').val();
          var description = $('#description').val();
          $.post('/user/save', {
                  email : email,
            name : name,
            surname : surname,
            role : role,
            telephone : telephone,
            description : description
              })
            .done(function(){
                    alert('<h2>The new user has been successfully added!</h2>', function(){
                        clearUserFields();
                window.location.reload();
                  });
              })
            .fail(function(){
                  alert('<h2>Sorry, an error occurred during the operation.<br>Please retry later...</h2>', function(){
                      window.location.reload();
                 });
             });

And this is the route in node.js

// routes file
var postgresql_db_controller = require('../controller/pose-postgresql-connection');
var Q = require ('q');
var bodyParser = require('body-parser');

// route for editing the user
/*
app.get('/user/edit', function(req, res){
  retrieveUserInfo().then(function(result){
    res.render('admin-profile.ejs', {
        title : 'Edit your profile',
        admin-info: result
    });
  });
});
*/

module.exports = function (app) {
  // route for routing to "adding a new user" page
  app.get('/user/add', function(req, res){
    res.render('new-user-profile.ejs', {
        title : 'Add a new user'
    });
  });

  //route for routing to "editing the admin user info" page
  app.get('/user/admin', function(req, res){
    res.render('admin-profile.ejs', {
        title : 'Admin profile'
    });
  });

  // route for adding and storing a new user into the postgresql databases
  app.post('/user/save', function(req, res){
    console.log("routes");
    console.log("req.body : " + req.body);
    var email = req.params.email;
    var name = req.params.name;
    var surname = req.params.surname;
    var role = req.params.role;
    var telephone = req.params.telephone;
    var description = req.params.description;
    // storing data into database
    postgresql_db_controller.postgresql_save_user(email, name, surname, role, telephone, description).then(function(result){
      if(result == null){
                res.writeHead(404);
                res.end();
                return;
            }
      // TO DO
      // manage the result (?)
      console.log(result);
      res.writeHead(200);
            res.end();
    });
  });

  // route for creating a new project


  // route for searching an existing project

};

and this is the other file:

var express = require('express');
var app = express();

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({
  extended: false
}));

app.use(bodyParser.json()); 

var Q = require ('q');

var cfenv = require('cfenv');

// Util is handy to have around, so thats why that's here.
const util = require('util');
// and so is assert
const assert = require('assert');

// Then we'll pull in the database client library
var pg = require('pg');

// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

// Within the application environment (appenv) there's a services object
var services = appEnv.services;

// The services object is a map named by service so we extract the one for PostgreSQL
var pg_services = services["pose-for-postgresql"];

// This check ensures there is a services for PostgreSQL databases
// assert(!util.isUndefined(pg_services), "Must be bound to pose-for-postgresql services");

// We now take the first bound PostgreSQL service and extract it's credentials object
var credentials = pg_services[0].credentials;

// Within the credentials, an entry ca_certificate_base64 contains the SSL pinning key
// We convert that from a string into a Buffer entry in an array which we use when
// connecting.
var ca = new Buffer(credentials.ca_certificate_base64, 'base64');
var connectionString = credentials.uri;

// We want to parse connectionString to get username, password, database name, server, port
// So we can use those to connect to the database
var parse = require('pg-connection-string').parse;
config = parse(connectionString);

// Add some ssl
config.ssl = {
  rejectUnauthorized: false,
  ca: ca
}

// set up a new client using our config details
var client = new pg.Client(config);

// This function to set up the connection with PostgreSQL database
module.exports.postgresql_database_connection = function() {
  client.connect(function(err) {
    if (err) {
     console.log(err);
    }
    else {
      client.query('CREATE TABLE IF NOT EXISTS users (email varchar(256) NOT NULL PRIMARY KEY, name varchar(256) NOT NULL, surname varchar(256) NOT NULL, telephone int NOT NULL, role varchar(256) NOT NULL, description varchar(256) NOT NULL)', function (err,result){
        if (err) {
          console.log(err);
        }
      });
    }
  });
};

// This function is to create and store a new user into the PostgreSQL database with all the needed information
module.exports.postgresql_save_user = function(email, name, surname, role, telephone, description) {
  console.log("reading parameters");
  var deferred = Q.defer();
  // set up a new client using our config details
  var client = new pg.Client(config);
  client.connect(function(err) {
    if (err) {
     console.log(err);
     deferred.reject();
    }
    else {
      var queryText = 'INSERT INTO users(email,name,surname,telephone,role,description) VALUES(?, ?, ?, ?, ?, ?)';
      client.query(queryText, [email, name, surname, telephone, role, description], function (error,result){
        if (error) {
         console.log(error);
         deferred.reject();
        }
        else {
         console.log("Saving the new user into the postegresql database: ");
         console.log(result);
         //check how result is printed and then manage it where called
         deferred.resolve(result);
        }
      });
    }
  });
  return deferred.promise;
};

It seems there is an error in:

req.params.email

it's not printing anything. I also tried to use req.body.param_name but nothing happen. You know what it is? Thank you in advance

I am struggling since I am trying to retrieve all the parameters of a POST request in node.js, but it's not gonna work.

Here the post request from the webpage:

var email = $('#email').val();
          var name = $('#name').val();
          var surname = $('#surname').val();
          var role = $('#role').val();
          var telephone = $('#telephone').val();
          var description = $('#description').val();
          $.post('/user/save', {
                  email : email,
            name : name,
            surname : surname,
            role : role,
            telephone : telephone,
            description : description
              })
            .done(function(){
                    alert('<h2>The new user has been successfully added!</h2>', function(){
                        clearUserFields();
                window.location.reload();
                  });
              })
            .fail(function(){
                  alert('<h2>Sorry, an error occurred during the operation.<br>Please retry later...</h2>', function(){
                      window.location.reload();
                 });
             });

And this is the route in node.js

// routes file
var postgresql_db_controller = require('../controller/pose-postgresql-connection');
var Q = require ('q');
var bodyParser = require('body-parser');

// route for editing the user
/*
app.get('/user/edit', function(req, res){
  retrieveUserInfo().then(function(result){
    res.render('admin-profile.ejs', {
        title : 'Edit your profile',
        admin-info: result
    });
  });
});
*/

module.exports = function (app) {
  // route for routing to "adding a new user" page
  app.get('/user/add', function(req, res){
    res.render('new-user-profile.ejs', {
        title : 'Add a new user'
    });
  });

  //route for routing to "editing the admin user info" page
  app.get('/user/admin', function(req, res){
    res.render('admin-profile.ejs', {
        title : 'Admin profile'
    });
  });

  // route for adding and storing a new user into the postgresql databases
  app.post('/user/save', function(req, res){
    console.log("routes");
    console.log("req.body : " + req.body);
    var email = req.params.email;
    var name = req.params.name;
    var surname = req.params.surname;
    var role = req.params.role;
    var telephone = req.params.telephone;
    var description = req.params.description;
    // storing data into database
    postgresql_db_controller.postgresql_save_user(email, name, surname, role, telephone, description).then(function(result){
      if(result == null){
                res.writeHead(404);
                res.end();
                return;
            }
      // TO DO
      // manage the result (?)
      console.log(result);
      res.writeHead(200);
            res.end();
    });
  });

  // route for creating a new project


  // route for searching an existing project

};

and this is the other file:

var express = require('express');
var app = express();

var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({
  extended: false
}));

app.use(bodyParser.json()); 

var Q = require ('q');

var cfenv = require('cfenv');

// Util is handy to have around, so thats why that's here.
const util = require('util');
// and so is assert
const assert = require('assert');

// Then we'll pull in the database client library
var pg = require('pg');

// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

// Within the application environment (appenv) there's a services object
var services = appEnv.services;

// The services object is a map named by service so we extract the one for PostgreSQL
var pg_services = services["pose-for-postgresql"];

// This check ensures there is a services for PostgreSQL databases
// assert(!util.isUndefined(pg_services), "Must be bound to pose-for-postgresql services");

// We now take the first bound PostgreSQL service and extract it's credentials object
var credentials = pg_services[0].credentials;

// Within the credentials, an entry ca_certificate_base64 contains the SSL pinning key
// We convert that from a string into a Buffer entry in an array which we use when
// connecting.
var ca = new Buffer(credentials.ca_certificate_base64, 'base64');
var connectionString = credentials.uri;

// We want to parse connectionString to get username, password, database name, server, port
// So we can use those to connect to the database
var parse = require('pg-connection-string').parse;
config = parse(connectionString);

// Add some ssl
config.ssl = {
  rejectUnauthorized: false,
  ca: ca
}

// set up a new client using our config details
var client = new pg.Client(config);

// This function to set up the connection with PostgreSQL database
module.exports.postgresql_database_connection = function() {
  client.connect(function(err) {
    if (err) {
     console.log(err);
    }
    else {
      client.query('CREATE TABLE IF NOT EXISTS users (email varchar(256) NOT NULL PRIMARY KEY, name varchar(256) NOT NULL, surname varchar(256) NOT NULL, telephone int NOT NULL, role varchar(256) NOT NULL, description varchar(256) NOT NULL)', function (err,result){
        if (err) {
          console.log(err);
        }
      });
    }
  });
};

// This function is to create and store a new user into the PostgreSQL database with all the needed information
module.exports.postgresql_save_user = function(email, name, surname, role, telephone, description) {
  console.log("reading parameters");
  var deferred = Q.defer();
  // set up a new client using our config details
  var client = new pg.Client(config);
  client.connect(function(err) {
    if (err) {
     console.log(err);
     deferred.reject();
    }
    else {
      var queryText = 'INSERT INTO users(email,name,surname,telephone,role,description) VALUES(?, ?, ?, ?, ?, ?)';
      client.query(queryText, [email, name, surname, telephone, role, description], function (error,result){
        if (error) {
         console.log(error);
         deferred.reject();
        }
        else {
         console.log("Saving the new user into the postegresql database: ");
         console.log(result);
         //check how result is printed and then manage it where called
         deferred.resolve(result);
        }
      });
    }
  });
  return deferred.promise;
};

It seems there is an error in:

req.params.email

it's not printing anything. I also tried to use req.body.param_name but nothing happen. You know what it is? Thank you in advance

Share Improve this question edited Jun 18, 2017 at 18:22 g_tech asked Jun 18, 2017 at 17:17 g_techg_tech 2511 gold badge4 silver badges14 bronze badges 4
  • will you please post full code of node.js part ? – Vivek Doshi Commented Jun 18, 2017 at 17:23
  • It would also be helpful if you could provide the version number of body-parser and express dependencies – XPLOT1ON Commented Jun 18, 2017 at 17:45
  • I updated the code above – g_tech Commented Jun 18, 2017 at 18:42
  • move /user/save router to server file to certain anything is right with express engine, maybe pass the express object cause this problem, just use res.json(req.body) in function @Giulio – farhadamjady Commented Jun 18, 2017 at 18:51
Add a ment  | 

3 Answers 3

Reset to default 2

Try to wrap the data in JSON.Stringify as below.

$.post('/user/save', JSON.Stringify({ email : email, name : name, surname : surname, role : role, telephone : telephone, description : description }))

If you get any error at JSON.Stringify, try to use Json data directly as below.

$.post('/user/save', "{ 'email' : email, 'name' : name, 'surname' : surname, 'role' : role, 'telephone' : telephone, 'description' : description }")

your code does not make use of bodyParser

in app.js (where you start node server), just below var app = express()

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

And your route file

// routes file
var postgresql_db_controller = require('../controller/pose-postgresql-connection');
var Q = require ('q');
var bodyParser = require('body-parser');

// route for editing the user
/*
app.get('/user/edit', function(req, res){
  retrieveUserInfo().then(function(result){
    res.render('admin-profile.ejs', {
        title : 'Edit your profile',
        admin-info: result
    });
  });
});
*/

module.exports = function (app) {
  // route for routing to "adding a new user" page
  app.get('/user/add', function(req, res){
    res.render('new-user-profile.ejs', {
        title : 'Add a new user'
    });
  });

  //route for routing to "editing the admin user info" page
  app.get('/user/admin', function(req, res){
    res.render('admin-profile.ejs', {
        title : 'Admin profile'
    });
  });

  // route for adding and storing a new user into the postgresql databases
  app.post('/user/save', function(req, res){
    console.log("routes");
    console.log("req.body : " + req.body);
    var email = req.body.email;
    var name = req.body.name;
    var surname = req.body.surname;
    var role = req.body.role;
    var telephone = req.body.telephone;
    var description = req.body.description;
    // storing data into database
    postgresql_db_controller.postgresql_save_user(email, name, surname, role, telephone, description).then(function(result){
      if(result == null){
                res.writeHead(404);
                res.end();
                return;
            }
      // TO DO
      // manage the result (?)
      console.log(result);
      res.writeHead(200);
            res.end();
    });
  });

  // route for creating a new project


  // route for searching an existing project

};

Check req.body after console.log("routes"); of your server file and see what parameters you are getting.

like this:-

console.log(req.body)

if you have body parser package then it will show you parameters list which are ing out from client. Once you get the parameters list, you can easily get like req.body.email .

Also change your ajax request like this:-

 $.post('/user/save', data: {
              "email" : email,
        "name" : name,
        "surname" : surname,
        "role" : role,
        "telephone" : telephone,
        "description" : description
          })
        .done(....

Also where is this code..

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json()) 

in your server file?

you need to add this in your app file to access bodyparser

发布评论

评论列表(0)

  1. 暂无评论