Server Code:
const express = require('express')
const app = express() app.use(express.static('public')) app.use(express.json({limit :'100mb'}));
app.post('/post', (req, res) => { console.log('post called');
console.log(req.body); ////Printed here
})
app.listen(3000)
Client code:
const data ={agent: 41} const options = { method: 'POST', mode: 'no-cors', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) };
fetch('http://localhost:3000/post', options);
output in server terminal
can anyone please tell me what am i doing wrong, how can i get the value?
Expected Output : {agent: 41}
CodePudding user response:
On you client code, why are you using mode: 'no-cors'
option?
Removing it will fix your problem.
const data = { agent: 41 }
const options = { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) };
fetch('http://localhost:3000/post', options);
Here you can find an explaination on what is happening.
If you were using mode: 'no-cors'
to handle a cors error, this is not the way to go. You should use the cors middleware in you Express based application.
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors()) // use it as first middleware