I am making a web app with a React frontend and a Node Express backend. When I send a POST request with a JSON body to one of my endpoints, and print the contents of req.body from the server, I get an empty object. However, when I send the exact same request from Postman, it works perfectly.
In the "network" tab of developer tools, I see this error message . The payload of the request seems to be correct.
Here is my frontend request code:
fetch('http://localhost:3000/building', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({buildingAttempt: 'test'}),
}).then(function (res) {
// deal with result
}).catch(function (error) {
console.log(error);
}).finally(function () {
});
On the backend, I print the contents of req.body to test:
app.use('/building', (req, res) => {
console.log(req.body);
// other code
}
I've already tried including the code snippet below to deal with origin issues:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
I've also added the json body parser:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
Why don't you try to use axios?? its way easier for you.
create a services folder, and inside it an api.js file
import axios from 'axios'
export const api = axios.create({
baseUrl: 'http://localhost:3000'
})
//file where you're making the request
import api from '...path...'
api.post('/building', { test: 'test data' })
Try using cors i think
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.