0
votes

I've been developing a React app to authenticate an user with express backend. I've tested out the express server by sending a POST request using postman and everything works fine.

But I'm getting a weird error while doing the same POST request using the React App. enter image description here

I checked out the request payload and the JSON data sent is correct.

Given below is the code snippet for axios action.

export const registerUser=(userData, history) => dispatch => {
    axios.post("http://localhost:5000/users/register",userData)
        .then( res => {
            console.log(res)
            history.push("/login") } )
}

Any pointers on how to solve this issue is much appreciated.

1
thanks, is it possible to get an encapsulated answer? I mean, the necessary codes I should add? - Nimrod
If you are serving your react app on different port than your server, please refer to this page, I have a feeling this might be a proxy issue create-react-app.dev/docs/proxying-api-requests-in-development - bullettrain

1 Answers

2
votes

On the backend you need to set cors, first add the cors package and use it like

 const app = express();

 app.use(cors());

this will allow all site to connect to your backend, you can restrict it so that only some site can use it like

app.use(
  cors({
    origin: "your app route",
  })
);