我正在努力,因为我试图在node.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 :(得分: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 }")
答案 1 :(得分:1)
在console.log之后检查req.body(&#34; routes&#34;);你的服务器文件,看看你得到了什么参数。
像这样: -class ControllerExtensionModuleMykmykpetBitrix24 extends Controller{
public function newOrderToCRM($orderID){
mail("mykmykpet@mykmykpet.xyz","Hello from OpenCart Event",$orderID);
}
}
如果您有身体解析器包,那么它将显示从客户端发出的参数列表。获得参数列表后,您可以轻松获得req.body.email。
同样更改你的ajax请求: -
console.log(req.body)
此代码也在哪里..
$.post('/user/save', data: {
"email" : email,
"name" : name,
"surname" : surname,
"role" : role,
"telephone" : telephone,
"description" : description
})
.done(....
在您的服务器文件中?
您需要在应用文件中添加此内容才能访问bodyparser
答案 2 :(得分:1)
您的代码未使用bodyParser
在app.js(你启动节点服务器),就在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
};