Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
fetch API in react sends empty body

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: "mjaberster@gmail.com",
            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 :(

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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'.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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!

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda