JSON parsing in Express

@senocular one one thing if you can clarify please,

-in back end i am using Node Express and the below code is working fine.
but can i achieve the same thing i.e saving the incoming data into the DB, like using without app.use(express.json()); statement. i did try to parse the body link x1 = req.body.json(); but that is coming up with error.

const express = require("express");
const mysqlx = require("mysql");
const app = express();
app.use(express.json());         // deleted this when parsing data below


app.post("/api/customers", (req, res) => {
let x1 = req.body;      // here i tried with let x1 = req.body.json();

  var person = { email: x1.name, password: x1.password };

  connection.query("INSERT INTO users SET ?", person, function (err, results) {

    if (err) throw err;

    console.log(results);

  });

  //query

  let q = "SELECT * from users";

  connection.query(q, function (err, results) {

    if (err) throw err;

    res.json(results);

  });

});

We’re getting off topic of the original thread so I created a new one for you :wink:

As for express, this is how express works. You set up the json middleware at the top with app.use() and that will be used to format values in req.body. body is just a data container. Its not used to format.

2 Likes

@senocular cool. got it now. Thanks alot :slightly_smiling_face: