I'm working on a web app and I'm sending a post request with ajax to a node+express backend. The problem is that in the backend the values for all parameters are NULL, I have checked by console.log(data)
on the front end before sending ajax request and I'm getting the values here but on the backend request.query
has all params with NULL values.
AJAX Request
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
Data : {first_name: 'a', last_name: 'a', email: 'admin@gmail.com', password: '13011301', job_title: 'CV-Specialist', …}
Backend Code
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");
}
}
);
});
Backend Response
{code: 'ER_BAD_NULL_ERROR', errno: 1048, sqlMessage: "Column 'first_name' cannot be null", sqlState: '23000', index: 0, …} code : "ER_BAD_NULL_ERROR" errno : 1048 index : 0 sql : "Insert into users (first_name,last_name,email,password,job,security,mobile,remarks) values (NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)" sqlMessage : "Column 'first_name' cannot be null"
I have searched for solutions and explanations but I can't figure out what's causing this. Any help or hints will be appreciated, thank!
1条答案
按热度按时间4zcjmb1e1#
The default content type header of jquery for Ajax is
application/x-www-form-urlencoded
. You are expected to send data in the query Params like so:Either send all of your data encoded in query params as shown above
or
set headers to
application/json
on the server side ensure you have body parser configured:
In your middleware callback get data in
req.body
instead ofreq.query
: