2017-06-18 41 views
2

我在努力嘗試檢索node.js中的POST請求的所有參數,但它不會工作。在節點js中獲取post請求的參數

這裏從網頁發佈請求:

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

而且這是在node.js中

// routes file 
var postgresql_db_controller = require('../controller/compose-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 

}; 

的路線,這是其他文件:

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["compose-for-postgresql"]; 

// This check ensures there is a services for PostgreSQL databases 
// assert(!util.isUndefined(pg_services), "Must be bound to compose-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; 
}; 

它似乎有錯誤:

req.params.email 

它不打印任何東西。我也嘗試使用req.body.param_name,但沒有發生。你知道這是什麼? 預先感謝您

+0

你會請發佈node.js部分的完整代碼嗎? –

+0

如果你可以提供body-parser的版本號和表達依賴關係,這也會很有幫助 – XPLOT1ON

+0

我更新了上面的代碼 – Giulio

回答

1

檢查console.log(「routes」)後的req.body。你的服務器文件,看看你得到什麼參數。

這樣的: -

console.log(req.body) 

,如果你有身體解析器包,那麼它會告訴你相關參數,從客戶端現身名單。一旦你得到參數列表,你可以很容易得到像req.body.email。

而且改變你的Ajax請求如下: -

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

而且這是哪裏代碼..

​​ 在您的服務器文件

,你需要在你的應用程序文件中添加此訪問bodyparser

+0

我試圖打印req.body,但它是未定義的。我不知道爲什麼 – Giulio

+0

是否確定在應用程序中安裝了body-parser軟件包? – noobcode

+0

是的,我很肯定 – Giulio

2

嘗試JSON.Stringify包中的數據如下。

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

如果您在JSON.Stringify上遇到任何錯誤,請嘗試直接使用Json數據,如下所示。

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

並且獲取所有參數我在路由文件中必須做些什麼? – Giulio

1

您的代碼不會使app.js使用bodyParser

(你啓動節點服務器),僅低於var app = express()

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

而且你的路由文件

// routes file 
var postgresql_db_controller = require('../controller/compose-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 

};