使用http-proxy-middleware配置setupProxy.js

时间:2019-01-20 21:39:51

标签: reactjs cors fetch-api http-proxy-middleware

我正在尝试使用HTTP代理中间件在create-react-app中配置代理服务器(setupProxy.js),以访问天气数据API(api.darksky.net)。

我遵循了React文档(https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development#configuring-the-proxy-manually)中的步骤,但是CORS仍然存在问题。

我已经尝试在我的提取调用中使用'https://cors-anywhere.herokuapp.com/'(https://github.com/Rob--W/cors-anywhere/)来添加API URL,但这确实可行,但是我觉得有点老套,我希望可以使用靠我自己。

以下是最终从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));
  }

这是我的setupProxy.js文件的代码:

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

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

此错误显示在我的控制台中:

  

跨域请求被阻止:“同源起源”策略不允许读取> https://api.darksky.net/forecast/ {myAPIKey} /9.739> 9056,-82.8484079上的远程资源。 (原因:CORS标头“ Access-Control-Allow-Origin”>丢失)。

2 个答案:

答案 0 :(得分:1)

在这种情况下,无需设置自定义代理...

只需将此添加到您的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"
  ]
}

然后在您的App.js中

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

它应该起作用...(请注意,所有异步调用都应在componentDidMount生命周期方法中完成...)

答案 1 :(得分:0)

代理在您的代码中放置错误,请尝试

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