【发布时间】:2019-06-14 07:53:33
【问题描述】:
我正在尝试使用 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”>缺失)。
【问题讨论】:
标签: reactjs cors fetch-api http-proxy-middleware