'I can't post on server?

JAVASCRIT, REACT, Node.js As you can see from the javascript code I am trying to add some on the server-side using method post but it can not post on the server. What I can change on my code.**

        const express = require('express');
const cors = require('cors');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
require('dotenv').config()
const app = express();

app.use(cors());
app.use(express());
                app.post('/items', async (req, res) => {
                    const newItem = req.body;
                    console.log(newItem);
                    const result = await laptopCollection.insertOne(newItem);
                    res.send(result);
                })

I think I am missing in middleware

    app.use(cors());
app.use(express());


Solution 1:[1]

I think correct middleware is:

app.use(cors())
app.use(express.json())

Post with async function

async function run() {
    try {
        await client.connect();
const laptopCollection=client.db('database_name').collection('collection_name');

       app.post('/items', async (req, res) => {
                    const newItem = req.body;
                    console.log(newItem);
                    const result = await laptopCollection.insertOne(newItem);
                    res.send(result);
                })
        // Add New Post
    } finally {
        // await client.close();
    }
}
run().catch(console.dir);

Solution 2:[2]

app.use(express()) function can't parses incoming JSON requests and also can't puts the parsed data in req.body.To solve the problem write the function as

app.use(express.json())

You also forget to import async function. You need to provide this codes:

async function run() 
{
  try {
    await client.connect();
    const laptopCollection=client.db('database_name').collection('collection_name');
  app.post('/items', async (req, res) => {
    const newItem = req.body;
    console.log(newItem);
    const result = await laptopCollection.insertOne(newItem);
    res.send(result);
  })
} 

Solution 3:[3]

Maybe the correct way is:

app.use(cors())
app.use(express.json())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Tyler2P
Solution 3 maxshuty