2

As stated in the title of this question, i'm having CORS issues with a fetch method. Here are the solutions i've tried. Obviously none have worked.

Actual console error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I tried to fix the issue via my Express server. I am configuring this before I establish my routes.

import cors from 'cors';

app.use(cors({
  origin: '*',
}));

Also tried it this way.

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

Client side service. Set {mode: 'cors'} object.

fetch(requestUrl, {mode: 'cors'}).then((response) => {
  return response.json();
}).then((restaurants) => {
  resolve(restaurants);
}).catch((err) => {
  reject(err);
});

At this point, i'm lost. I'm just trying to get data back from google maps api. Any help would be grateful.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Josh
  • 1,455
  • 19
  • 33
  • make sure you are adding cors before registering any route, and try using app.use(cors()); – Siraj ul Haq May 09 '18 at 14:12
  • 1
    The Google Maps API is intentionally not CORS enabled. You can’t call it from fetch. Instead you need to follow the API documentation and use it as documented. See the answer at https://stackoverflow.com/questions/44336773/google-maps-api-no-access-control-allow-origin-header-is-present-on-the-reque/44339169#44339169 – sideshowbarker May 09 '18 at 14:21
  • @sideshowbarker Thanks for the input. I see how this could work. However, my react application is very modular. So for me to get access to this service would be a headache.. I may just update the client side service code and create a route in my express app. That way i can set cors. I just hate to contact my server to retrieve 3rd party data. Guess it has to be done from time to time though. – Josh May 09 '18 at 14:46

0 Answers0