Ajax & Node JS:参数值在后端为空



我正在一个web应用程序上工作,我正在发送一个post请求与ajax的节点+express后端。问题是,在后端所有参数的值都是NULL,我已经检查了console.log(data)在前端发送ajax请求之前,我在这里得到的值,但在后端request.query具有NULL值的所有参数。

AJAX请求

const data = {
first_name: fn,
last_name: ln,
email: email,
password: password,
job_title: job,
security: security,
mobile: mobile,
remarks: remarks,
};
console.log("Data : ");
console.log(data);
$.post(
"http://127.0.0.1:4000/user/add",
data,
function (response) {
console.log(response);
}
);

Console Log For Data

数据:{first_name: 'a', last_name: 'a', email: 'admin@gmail.com',密码:'13011301',job_title: 'CV-Specialist',…}

后端代码

app.post("/user/add", (req, res) => {
const data = req.query;
var sql =
"Insert into users (first_name,last_name,email,password,job,security,mobile,remarks) values (?,?,?,?,?,?,?,?)";
conn.query(
sql,
[
data.first_name,
data.last_name,
data.email,
data.password,
data.job,
data.security,
data.mobile,
data.remarks,
],
function (err, result) {
if (err) {
res.send(err);
} else {
res.send("1 record inserted");
}
}
);
});
<<p>后端响应/strong>

{code: 'ER_BAD_NULL_ERROR', errno: 1048, sqlMessage: "Column 'first_name'不能为null", sqlState: '23000', index: 0,…}代码:"ER_BAD_NULL_ERROR"errno:1048指数:0sql:在用户(first_name,last_name,email,password,job,security,mobile, comments)中插入值(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)"sqlMessage:列'first_name'不能为空

我已经寻找了解决方案和解释,但我不知道是什么原因造成的。任何帮助或提示将不胜感激,谢谢!

Ajax的jquery默认的内容类型头是application/x-www-form-urlencoded。您应该像这样在查询参数中发送数据:

$.ajax({
url: 'http://www.example.com?' + $.param({first_name: 'a', last_name: 'a', email: 'admin@gmail.com', password: '13011301', job_title: 'CV-Specialist', …}),
method: 'POST'
});

发送所有编码在查询参数中的数据,如上面所示

set headers toapplication/json

$.ajax({
url: 'YourRestEndPoint',
headers: {
'Content-Type':'application/json'
},
method: 'POST',
data: data,
success: function(data){
console.log('succes: '+data);
}
});

服务器端的确保配置了正文解析器:

const bodyParser = require('body-parser');
.
.
.
.
.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

在你的中间件回调得到数据在req.body而不是req.query:

app.post("/user/add", (req, res) => {
const data = req.body;
var sql =
"Insert into users (first_name,last_name,email,password,job,security,mobile,remarks) values (?,?,?,?,?,?,?,?)";
conn.query(
sql,
[
data.first_name,
data.last_name,
data.email,
data.password,
data.job,
data.security,
data.mobile,
data.remarks,
],
function (err, result) {
if (err) {
res.send(err);
} else {
res.send("1 record inserted");
}
}
);
});

相关内容

最新更新