Home > Software engineering >  fetch API in react sends empty body
fetch API in react sends empty body

Time:02-25

I have a sample app of react that should post data to nodejs, the code in the react side looks as:

export const RegisterUser = async (user, userContext) => {

   fetch('http://localhost:3001/user/register', {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
        },
        body: JSON.stringify({
            username: "mjaberster",
            fullName: "Marwan Jaber",
            password: "P@$$w0rd1234",
            email: "[email protected]",
            phoneNumber: " 972532203407"
        }),
        mode: 'no-cors'
    }).then((res) => {
        console.log(`Trying to convert response to JSON ${JSON.stringify(res)}`)
        if(res.ok) {
            res.json().then(data => {
                console.log(JSON.stringify(data))
                return JSON.stringify(data)
            })
        } else {
            console.log(res.status)
            console.log(res.statusText)
            return `User failed to register due to an error (${res.status}, ${res.statusText}`
        }
        
    }).catch(err => {
        userContext.loginMsg= err.message
        userContext.loginStatus= err.status
        userContext.token= null
        console.log(`User failed to register due to an error (${err.message}, ${err.status}`)
        return `User failed to register due to an error (${err.message}, ${err.status}`
    })
}

and the code in the node looks as:

server.use(express.json())
server.post(`/user/register`, async (req, res) => {
    const user = req.body
    console.log(`>>>> ${user}`)
    if(!user) {
        const err = new Error("User must be submited")
        err.status = 400
        throw err
    }
    const addedUser = await MongooseConnector.addUser(user)
    if(addedUser) {
        res.json({message: "User has been added successfuly"})
    } else {
        res.status(500).json({message: "An error occured, couldn't create user, please try again later"})
    }
})

When I send the same body object from postman, I get the expected result When I send the request with the same body from react, I get: in the log of node:

>>>> undefined
undefined

in the log of react: POST http://localhost:3001/user/register net::ERR_CONNECTION_REFUSED

I'm getting crazy, please help :(

CodePudding user response:

You said mode: 'no-cors' which causes fetch to silently drop anything which requires CORS permissions. This includes setting the Content-Type for a JSON formatted request.

Since the client isn't telling the server that the body is JSON, the body parsing middleware isn't parsing it.

Don't use mode: 'no-cors'.

CodePudding user response:

I just switched from fetch to axios, and everything worked fine! here is what I did:

var axios = require('axios');
var data = JSON.stringify({
  "username": user.username,
  "fullName": user.fullName,
  "password": user.password,
  "email": user.email,
  "phoneNumber": user.phoneNumber
});

var config = {
  method: 'post',
  url: 'http://localhost:3001/user/register',
  headers: { 
    'Content-Type': 'application/json'
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(response.data.message);
})
.catch(function (error) {
  console.log(error);
});

I'm not sure what is the reason fetch function is doing this to me, but maybe it has a bug!

  • Related