0

My error message: "Failed to load http://localhost:8080/db: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access."

My front end server is running on localhost:3000

componentDidMount() {
  axios
    .get('http://localhost:8080/db')
    .then(response => console.log(response))
    .catch(err => console.log(err));
}

This is in my express file:

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );
  res.setHeader(
    'Access-Control-Allow-Methods',
    'POST, GET, PATCH, DELETE, OPTIONS'
  );
  next();
});
  • 1
    Do you have a server running at port 8080 ? – Vipul Singh Jan 22 '18 at 20:01
  • New error message: "Failed to load http://localhost:8080/db: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access." – Sky Jacobson Jan 22 '18 at 20:13
  • This is a CORS error, and so you might want to do some research on that...then update the question with a more specific question if you still have issues. Also, I think you should try either `res.header()` or `res.set()`, since it's not clear to me that `setHeader` [works](https://stackoverflow.com/questions/23751914/how-can-i-set-response-header-on-express-js-assets#23759686) (note that I'm not an express expert). – user Jan 22 '18 at 21:21

3 Answers3

0

This looks like your server is not running at all, or not on that port.

You have to tell express where to listen with a line like:

app.listen(8080, () => console.log('Example app listening on port 8080!'))

then run it with (supposing your server code is in a file named app.js)

node app.js
Martin
  • 7,634
  • 1
  • 20
  • 23
  • Sorry I forgot to run the server when I asked the question. This is the actual error message I needed to address: "Failed to load http://localhost:8080/db: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access." – Sky Jacobson Jan 22 '18 at 20:15
0

I was able to resolve this by installing this package and enabling all cors.

https://github.com/expressjs/cors

0

If you are running it in chrome. Please use the below extension to make it work.

enable cross-origin.

You can enable the cross-origin from backend code as well.

Japar Sathik
  • 121
  • 5