React app using API with another origin (CORS)

Install this.

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=es

Once installed, click on his BrowserIcon and toggle on. It is all. You will not receive more error.

EDIT. Solution for Production If you want config it from your server (or simply not adding a browser extension, try this:)

  • If you are using node.js do the following: node.js server file: response.writeHead(200, { 'Content-Type': contentType, 'Access-Control-Allow-Origin': '*' })

  • fetch('http://ajax.googleapis.com/ajax/services/feed/load?v=‌​1.0&num=8&q=http://r‌​ss.cnn.com/rss/editi‌​on_entertainment.rss‌​?output=rss', { method: 'get', mode: 'no-cors', }).then(() => { console.log('Works!'); });

  • Other solution:If you are using PHP too you can add: <?php header('Access-Control-Allow-Origin: *'); ?> into your PHP File. As I see, it is not the case, so... In your server (eg: Apache) add this directive: Header set Access-Control-Allow-Origin * in Settings (as the first option).


To add more on existing answers.

With react you can use "proxy" in your package.json to avoid CORS. Basically if you need to reach localhost:8100 (your java backend) and your react app run on localhost:3000

You can set:

In your package.json

"proxy": "http://localhost:8100"

And then when you want to make a get to /hello which would be an endpoint of your java API you can do:

import axios from 'axios';

axios.get('/hello')
  .then(resp => {
    console.log(resp.data);
  });

And it will be redirected to http://localhost:3000/hello so you will avoid CORS.


I just want to share how I make my local development painless by this post if you are using create-react-app by just adding your main API url proxy to your package.js for example "proxy": "http://localhost:8080/API" No need to setup CORS on your backend.


So, I solved the problem by using another stackoverflow thread and robertklep's comment. As stated here: "When working on localhost, the cookie domain must be omitted entirely.". I implemented robertkleps idea, but did not set the domain. It resulted in a Set-Cookie like this: Set-Cookie:kek=7fukucsuji1n1ddcntc0ri4vi; Version=1; Path=/; Max-Age=100000. This works fine.