1

I'm trying a POST fetch request to my api server for react and no matter how i send the data, i keep getting Unexpected token o in JSON at position 1.

handleSubmit:

event.preventDefault();
    fetch('http://localhost:3001/user/register',{
        method:'POST',
        headers:{
            'Content-Type':'application/json'
        },
        body:this.state
    })
    .then(data => data.json())
    .then(data =>{
        if(data.success) console.log('It works');
        else console.log(data.info + data.success);
        console.log(this.state);
    });

And my api app.post:

app.post('/user/register', (req, res)=>{
res.setHeader('Content-Type', 'application/json');

console.log('Commiting to register');
console.log(req.body);
let user = new userModel({
    firstName:req.body.firstName,
    lastName:req.body.lastName,
    age:req.body.age,
    email:req.body.email,
    username:req.body.username,
    password:req.body.password
});
user.save()
.then((info)=>{
    let data = {success:true, info:info};
    res.send(data);
})
.catch((err)=>{
    let data = {success:false, info:err};
    res.send(data);
});
console.log('Registering processed');

})

2 Answers2

0

You could try to use res.json(data) instead of res.send(data) this sets your response content-type to application/json

On the client side you can also do JSON.parse(data) on the data received from your fetch response.

Nevikk
  • 45
  • 6
  • "You could try to use res.json(data) instead of res.send(data) this sets your response content-type to application/json" Just did that, now i get 400 bad request "On the client side you can also do JSON.parse(data) on the data received from your fetch response" Did it before, no change at all – Dragnea Andrei Aug 11 '21 at 16:43
0

Long story short the problem was above what i posted, i used express.json() as a middleware which was what i needed but i didn't use it properly. Using express.json() as middleware expects the body of the request to be a string so that it can convert it into json, so in react i used JSON.stringify(jsonObject) where jsonObject was the fetch body content that i needed.