mysql Ajax & Node JS : Paramaters values are NULL in backend

ivqmmu1c  于 2022-12-22  发布在  Mysql
关注(0)|答案(1)|浏览(114)

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!

4zcjmb1e

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:

$.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'
});

Either send all of your data encoded in query params as shown above
or
set headers to application/json

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

on the server side ensure you have body parser configured:

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

In your middleware callback get data in req.body instead of 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");
      }
    }
  );
});

相关问题