gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:22:47 29 4
gpt4 key购买 nike

我正在尝试使用 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/”作为 API URL 的前缀。 ' ( https://github.com/Rob--W/cors-anywhere/ ),这正在工作,但对我来说感觉有点老套,我宁愿自己完成这个工作。

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

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

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).

最佳答案

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

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

关于reactjs - 使用 http-proxy-middleware 配置 setupProxy.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54281256/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com