1

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 :(

2
  • So your problem a connection problem or an empty body problem? I'm confused. Commented Feb 24, 2022 at 18:35
  • Me too, as you can see in the code, I have a body, and as you can see from the log of nodejs, I reach the handler function! Commented Feb 24, 2022 at 18:40

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

I tried without no-cors, it didn't help! I guess there is a problem with the fetch function, maybe something related to the Mac M1 processor, same code used to work in my old mac pro
I also think this is the issue, but simply removing the mode: 'no-cors' wont solve the issue alone you will need to also implement cors in your node js server. it is easy to set up

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.