Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fix a network error received from axios response reactjs

Tags:

reactjs

axios

I'm making a post request using axios in reactjs after users login. Here it is:

axios.post('https://localhost:3000/api/login/authentication', {
  email: email,
  password: password
})
.then(response => {
  this.props.history.push('/Main')
})
.catch(error => {
  console.log(error)
})

It goes in the error and I log it to the console. This is what I get:

Error: "Network Error" createErrorhttp://localhost:3000/static/js/0.chunk.js:26742:15 handleErrorhttp://localhost:3000/static/js/0.chunk.js:26293:14

Also in case it's any help, I get this warning before the error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:3000/api/login/authentication. (Reason: CORS request did not succeed)

Can anyone please help me solve this issue? Thanks in advance!

like image 791
tee Avatar asked Dec 02 '18 04:12

tee


Video Answer


1 Answers

If you're using a front-end application that makes request to a back-end API, you need to include certain headers in the API server if the API server is running on a different port.

For example, if you're serving a ReactJS application with webpack in development mode, webpack acts as a server, sending the reactJS application to the client. Then, making requests to the API server will require that the API server, running on a different port, include Access-Control-Allow-Origin headers in all http responses.

Basically, before generating every response, you need to set 'Access-Control-Allow-Origin' to localhost:<port you visit in the browser>.

In a basic express app, you can paste this in your app.js file, for example:

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:3001');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );
  next();
});

Note: If you may need to change http://localhost:3001 to match the port you visit in the browser.

EDIT: OP is not using express, but is using Webpack. The question is: What is an express-agnostic solution?

Answer: The solution is still the same: regardless of what API server you are using, just set the response headers for every response.

There is another solution that involves Webpack, though:

In the package.json file of your front end code that's being served with webpack, add the following: "proxy" :"http://localhost:<port API server is running on>"

For example, is webpack is serving your front end app to localhost:3000 and your api server is running on localhost:3001, then the proxy in package.json would be:

"proxy":"http://localhost:3001"

like image 123
Wilfred Tannr Allard Avatar answered Oct 07 '22 14:10

Wilfred Tannr Allard