2

我正在尝试使用 HTTP-proxy-middleware 在 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。

我已经尝试在我的 fetch 调用中使用“ 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”>缺失)。

4

2 回答 2

3

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

只需将其添加到您的 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 生命周期方法中完成......)

于 2019-01-20T23:35:54.630 回答
1

代理在您的代码中放置错误,请改用此方法

app.use("/forecast", 
   proxy({
      target: "https://api.darksky.net/",
      changeOrigin: true
   })
);
于 2019-11-23T08:56:58.090 回答