Languages
[Edit]
EN

Express.js - send json to node server

0 points
Created by:
Kia-H
546

In this article, we would like to show you how to get JSON from requests in Express.js.

The request data are passed in the request.body property. 

1. Get JSON from requests example

Note: it is required to add external library to run below example, so use:

npm install express

JSON received from the client in the POST request:

{
  "title": "example title", 
  "text": "example text"
}

Practical code:

const express = require('express');

const port = 3000;
const app = express();

app.use(express.json()); // middleware to parse JSON   

app.post('/tasks/', (request, response) => {
  const title = request.body.title;  // title = "example title"
  const text= request.body.text;  // text = "example text"
  // Here we can sends a query to the database

  if (error) {
    response.status(500).send({ error: error });
  } else {
    response.sendStatus(200)
  }
});

app.listen(port, () => {
  console.log(`server is listening at http://localhost:${port}`);
});

Note: to read the JSON contained in the request, we must use express.json() middleware.

2. Pure JavaScript (Vanilla JS) AJAX POST request

The following is an example execution of a fetch method that sends JSON via POST request.

<!DOCTYPE html>
<html>
  <body>
    <script>

      var task = {
        title: 'example title',
        text: 'example text'
      }

      fetch('/tasks', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(task),
      })
        .then((response) => response.json())
        .then((data) => {
          console.log('Success:', data);
        })
        .catch((error) => {
          console.error('Error:', error);
        });

    </script>
  </body>
</html>

Alternative titles

  1. Express.js - receive JSON from requests
  2. Express.js - get JSON from requests
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join