Home > Net >  I can't post on server?
I can't post on server?

Time:05-08

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());

CodePudding user response:

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);
})
} 

CodePudding user response:

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);

  • Related