Ericson Willians
Ericson Willians

Reputation: 7845

'Access-Control-Allow-Origin' when using axios and express

I have a start_express.js file and I run it with node:

const express = require("express"); 

const app           = express(),  
      DEFAULT_PORT  = 5000

app.set("port", process.env.PORT || DEFAULT_PORT);
app.get("/whatever", function (req, res) {
    res.send("It works!");
    console.log("Something's wrong");
});

var server = app.listen(app.get("port"));

I my react app, I have a handleSubmit method that tries to get that response:

handleSubmit(event) {
    axios.get('http://127.0.0.1:5000/whatever')
      .then(function (response) {
        alert(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    event.preventDefault();
}

When I click on submit, the start_express server prints "Something's wrong", but the alert on the client never works. It gives me the following error:

Failed to load http://127.0.0.1:5000/whatever: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

How am I supposed to send requests from the client if I can't respond?

Upvotes: 1

Views: 4033

Answers (2)

Ossip
Ossip

Reputation: 1045

Yes is confusing. But as the error message says, you need to set the Access-Control headers - on the server. The client part is fine. Using express the easiest way is probably with the cors package:

$ npm install cors

this way you'd allow all access - which you probably only want for testing:

const express = require("express"); 
const cors = require('cors');

const app           = express(),  
      DEFAULT_PORT  = 5000

app.use(cors());

...

see the nice doc here: https://github.com/expressjs/cors

Upvotes: 1

d3l33t
d3l33t

Reputation: 890

You are serving the site from port 3000 http://localhost:3000 and therefor the browser is doing its job at protecting you from accessing a site that doesnt allow cross origins.

Simple enable CORS for express https://github.com/expressjs/cors

You can even enable CORS just during development for security reasons

if (process.env.NODE_ENV !== 'production) { app.use(cors()) }

Upvotes: 1

Related Questions