I am sending json data from react application using fetch API but in server I'm getting req.body as empty.What's the problem I don't know
Here is my codeReact code
import './App.css';
function App() {
function handleClick() {
// Send data to the backend via POST
fetch('http://localhost:8000/message', { // Enter your IP address here
method: 'POST',
header:{'Content-Type':'application/json'},
body: JSON.stringify({name:"ROHIT"}) // body data type must match "Content-Type" header
})
}
return (
<div className="App">
TO DO App by Rohit Satpute
<button onClick={handleClick} style={{
}}>
Send data to backend
</button>
</div>
);
}
export default App;
const express=require('express');
const cors=require('cors');
const mongoose=require('mongoose');
const MySchema=require('./myschema.js');
const app=express();
app.use(cors());
app.use(express.json());
app.post('/message',(req,res)=>{
console.log(req.body);
res.json("rohit");
})
app.listen(8000,()=>{
console.log("server is running on port 8000");
})
I tried to find in what format does the fetch API is sending data to server.But in req of server it is nowhere.
CodePudding user response:
There are three mistakes in your code that are needed to be corrected.
- n the fetch api you need to use
headers
instead ofheader
. for example:
fetch('http://localhost:8545/message', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Rohit' }),
})
.then((res) => res.json())
.then((res) => console.log(res));
2: You cannot access req.body without using the
app.use(express.json({ extended: false }));
3: You need to whitelist your IP in the cors origin or you can allow access to every request using *. For example:
const cors = require('cors');
app.use(
cors({
origin: '*',
})
);