0

I'm getting this error on my React app. "Failed to load https://app-name.herokuapp.com/users/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access."

Code in my Express app

 var express = require('express');
 var router = express.Router();

 router.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, X-Auth-Token, Accept");
      next();
  }

Code in my Redux fetch call

 return dispatch => {
    const url = "https://app-name.herokuapp.com/users/";
    return fetch(url, {
      method: 'GET',
      mode: 'cors',
    })
    .then(handleErrors)
    .then(res => res.json())....
John White
  • 121
  • 4
  • 20

2 Answers2

1

That's an issue with your WebService, that happens when you are pointing from a domain to a different domain, like I'm pointing from localhost:3000 to localhost:3001, those are different, you should enable CORS in your WebService to allow that request.

You have to look for a way to enable CORS in your Heroku app, as I know, the external API calls are blocked in free domains, but don't know with Heroku.

Joseph Arriaza
  • 12,014
  • 21
  • 44
  • 63
  • So should my port in my heroku be pointing to 3001 too? Because that's what's happening in my react app – John White Aug 13 '18 at 20:16
  • You should allow CORS in your Heroku app. Maybe it could help: https://stackoverflow.com/questions/11001817/allow-cors-rest-request-to-a-express-node-js-application-on-heroku – Joseph Arriaza Aug 13 '18 at 20:43
  • I have a public fetch API. But some people were telling to enable CORS as it blocks their requests. I know there is an npm package called cors. But I saw that many Public APIs do not have CORS enabled. I also read some articles about the security risks in CORS. **I was asking that will it be wrong to enable CORS**. Few people are calling the API from the client-side code that is running in the browsers. Any suggestion is gratefully accepted. – Dron Bhattacharya Feb 25 '22 at 06:09
0

I figured it out. All I had to do was push to my heroku app. I didn't know it had its own git repo. Facepalm.

John White
  • 121
  • 4
  • 20