Accepting data: Handling JSON Data

Learn how to make your custom web server accept data in JSON format.

Managing incoming JSON data requires parsing it from the received POST request. Using an npm package like body-parser is the easiest solution. Install it with the npm install body-parser command or directly in your app dependencies.

  "dependencies": {
...
"body-parser": "^1.17.2"
  },

Then, add the following code towards the beginning of your server main file.

  // Load the body-parser package as a module
  const bodyParser = require("body-parser");

  // Access the JSON parsing service
  const jsonParser = bodyParser.json();

The following code handle POST requests to the "/api/cars" route. JSON data is parsed by jsonParser and defined as the request body.

  // Handle submission of a JSON car array
  app.post("/api/cars", jsonParser, (request, response) => {
const cars = request.body;
response.send(`You sent me a list of cars: ${JSON.stringify(cars)}`);
  });

Get hands-on with 1400+ tech skills courses.