Proxy not working for sending requests from one port to another

I’m trying to build a simple web app using the MERN stack while following a course.

My backend runs on port 5000 while react runs on port 3000. When I want to make a request with the backend API, it sends it to port 3000 instead of 5000. I keep on getting this error message:

xhr.js:178 POST http://localhost:3000/api/users 400 (Bad Request)

I included "proxy" : "http://localhost:5000" in my package.json. I tried replacing ‘localhost’ with 127.0.0.1. I tried deleting and reinstalling the package-lock.json and node_modules folders. I tried removing the proxy and using the entire url. I tried installing http proxy middleware. I tried enabling CORS on the backend too.

Either I’m cursed or doing everything wrong.

I’m using axios for handling the requests, here’s the code.

const config = {
     headers: {
         'Content-type': "application-json"
     }
}

const body = JSON.stringify(newUser)
const res = await axios.post('/api/users', body, config)
console.log(res.data)

Answer

Definetely not a proxy issue. The problem might be that you’re passing the body as a JSON string to the axios post() method. No need to do that, just pass the object:

const res = await axios.post('/api/users', newUser, config)

Also, the correct value for Content-type is application/json (not application-json)