[Fixed] express post request body shows up as empty

Issue

server code

const express = require('express');
const app =  express();

app.use(express.json());
app.use(express.urlencoded({ extended:true }));

app.post('/',(req,res)=>{
    console.log(req.body)
})

client code

const data = {idk:'stuff',idk2:'otherstuff'};

fetch('http://localhost:4000', {
    method:'POST',
    headers:{'Content-Type': 'application/json'},
    mode:'no-cors',
    body: JSON.stringify(data)
})

terminal shows: {}
tried pretty much everything so help would be very much appreciated thanks in advance:)

Solution

You said mode: 'no-cors' which tells fetch to silently ignore anything which requires CORS permission.

Setting the Content-Type to application/json requires CORS permission so your request is sent with Content-Type: text/plain instead.

This doesn’t trigger the JSON body parser.

Leave a Reply

(*) Required, Your email will not be published