0

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.

Nimrod
  • 375
  • 1
  • 12
  • Does this answer your question? [XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header](https://stackoverflow.com/questions/35553500/xmlhttprequest-cannot-load-xxx-no-access-control-allow-origin-header) – casraf Jan 14 '21 at 14:47
  • thanks, is it possible to get an encapsulated answer? I mean, the necessary codes I should add? – Nimrod Jan 14 '21 at 14:49
  • 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 https://create-react-app.dev/docs/proxying-api-requests-in-development/ – bullettrain Jan 14 '21 at 14:50

1 Answers1

2

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",
  })
);
Neezar
  • 56
  • 1
  • 1
  • 4