📜  express json body - Javascript (1)

📅  最后修改于: 2023-12-03 14:41:04.454000             🧑  作者: Mango

Express JSON Body - JavaScript

Express is a popular web framework for creating API's in JavaScript. One of its core features is its ability to parse HTTP requests and responses, including JSON data in the request body. In this tutorial, we will explore how to work with JSON data in the request body of your Express application.

Installing Express

First, we need to install Express. You can install it using npm:

npm install express
Creating a Simple Express Application

Let's create a simple Express application that listens for requests on port 3000:

const express = require('express');

const app = express();

app.listen(3000, () => {
    console.log('Server listening on port 3000');
});

When you run the above code using Node.js, you should see the message "Server listening on port 3000".

Parsing JSON Data in the Request Body

To parse JSON data in the request body, we need to use the built-in json middleware provided by Express. To use it, we need to call express.json() in our application. Here's an example:

const express = require('express');

const app = express();

app.use(express.json());

app.post('/api/user', (req, res) => {
    const user = req.body;
    console.log(user);
    res.send('User data received');
});

app.listen(3000, () => {
    console.log('Server listening on port 3000');
});

In the above code, we have added the express.json() middleware to our application. This middleware parses any incoming JSON data in the request body and makes it available in the req.body object.

We have also added a route /api/user that listens for POST requests. When a POST request is sent to this route, our server receives the JSON data in the request body and logs it to the console.

Testing the Application

To test the above application, we can send a POST request to the /api/user route with some JSON data in the request body. Here's an example using the fetch API:

fetch('/api/user', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        name: 'John Doe',
        email: 'johndoe@example.com'
    })
})
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));

This code sends a POST request to the /api/user route with a JSON object in the request body containing the name and email properties.

Conclusion

In this tutorial, we have explored how to work with JSON data in the request body of an Express application. We have used the express.json() middleware to parse the JSON data in the request body and made it available in the req.body object. This makes it easy to work with JSON data in an Express application.