Im sending a request to my local server in my react app like this
fetch("http://localhost:4000/signup", {
method: "POST",
mode: "no-cors",
body: JSON.stringify({ name: "Joe", lname: "Doe" }),
headers: {
"Content-Type": "application/json",
},
})
And the problem is that im getting empty object on the req.body on my local server.
app.post('/signup', (req, res) => {
console.log(req.body);
console.log('post request sent');
})
How could i fix it that i could see the content which is being sent from the fetch body?
CodePudding user response:
You appear to have two problems here each of which, by themselves, would cause the symptoms you describe.
First, as per the documentation for req.body:
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().
You don't seem to have loaded the JSON body-parsing middleware.
Second, you said mode: "no-cors" which tells fetch to silently ignore any attempts to do anything which would require permission from CORS.
This includes setting the Content-Type: application/json header which is needed to trigger the JSON parsing middleware.
So remove mode: "no-cors" and add the cors middleware to your server-side code.
CodePudding user response:
use axios for api request and try this hope so it will work
const data= { name:'zafar',lname:"niazi" };
axios.post('https://localhost:4000/signup', data)
.then(data){
console.log(data); });
