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