Configuring setupProxy.js using http-proxy-middleware

kelly_james picture kelly_james · Jan 20, 2019 · Viewed 14.2k times · Source

I am trying to configure a proxy server ( setupProxy.js ) within a create-react-app using HTTP-proxy-middleware to get access to a weather data API ( api.darksky.net ).

I followed the steps within the React documentation ( https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development#configuring-the-proxy-manually ) but am still having issues with CORS.

I have tried prepending my API URL within my fetch call with 'https://cors-anywhere.herokuapp.com/' ( https://github.com/Rob--W/cors-anywhere/ ) and this is working, but it feels a little corny to me and I'd rather get this working on my own.

Here is the function that is ultimately being called from within componentDidMount:

  fetchWeatherDataAuto = () => {
    let lat = this.state.locInfo.lat;
    let lon = this.state.locInfo.lon; 

    fetch(`https://api.darksky.net/forecast/${apiKey.darkSky_key}/${lat},${lon}`)
      .then(response => response.json())
      .then(response => console.log("Weather Response: ", response));
  }

Here is the code that is my setupProxy.js file:

const proxy = require('http-proxy-middleware');

module.exports = function(app) {
    app.use(proxy("/forecast", {
          target: "https://api.darksky.net/",
          changeOrigin: true
    }));
}

This error is shown in my console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading >the remote resource at >https://api.darksky.net/forecast/{myAPIKey}/9.739>9056,-82.8484079. (Reason: CORS header ‘Access-Control-Allow-Origin’ >missing).

Answer

SakoBu picture SakoBu · Jan 21, 2019

There is no need to set a custom proxy in this case...

Simply add this to your package.json:

{
  "name": "test1",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.7.0",
    "react-dom": "^16.7.0",
    "react-scripts": "2.1.3"
  },
  "proxy": "https://api.darksky.net", // <= add this here...
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

Then in your App.js

  componentDidMount() {
    fetch(`/forecast/${YOUR_API_KEY_HERE}/${lat},${lon}`)
      .then(response => response.json())
      .then(response => console.log('Weather Response: ', response));
  }

And it should work... (note that all async calls should be done in the componentDidMount lifecycle method...)