在create-react-app中有个proxy设置,看介绍好像是代理的意思,可以解决cros跨域的问题,但是设置好像没有起什么作用,还是有跨域问题,不知道有没有人用过?
在create-react-app中有个proxy设置,看介绍好像是代理的意思,可以解决cros跨域的问题,但是设置好像没有起什么作用,还是有跨域问题,不知道有没有人用过?
刚刚也遇到这个问题,想在项目中调用天气api,但是在webpack.config.dev.js
里怎么设置devSever.proxy都不行,然后看到了你的问题,试了一下。(在postman测试的地址是https://api.seniverse.com/v3/weather/now.json?key=${key}&location=${city}&language=zh-Hans&unit=c
)在package.json
里加了一行"proxy": "https://api.seniverse.com"
,再调用/v3/weather/now.json?key=${key}&location=${city}&language=zh-Hans&unit=c
,成功。谢谢。不过不知道原因
服务器得允许跨域才行,如你的配置http://news-at.zhihu.com/api
,得知乎服务器端配置
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
才可以。
这个一般用于开发环境中配置代理服务器,用来模拟数据什么的。
这个方式确实可以,只是看到create-react-app文档中说可以设置proxy代理,但是自己又试不出来。。
下面是网上一些人写的10-reasons-i-love-create-react-app 4. The Server Proxy
Almost all my recent projects are single-page apps that load a behemoth of .js code and once started it starts getting data from a REST server built in Django or Go or something. So, realistically the app looks like this:
componentDidMount() {
fetch('/api/userdata/')
.then(r = r.json())
.then(response => {
this.setState({userData: response.user_data})
})
}
With create-react-app you just add this line to your package.json:
"proxy": "http://localhost:8000"
Now, when you open http://localhost:3000 in the browser and the AJAX kicks off the browser thinks it's talking to http://localhost:3000/api/use... but the Node server that create-react-app ships with just automatically passes that on to http://localhost:8000/api/use... (This example just changes the port but note that it's a URL so the domain can be different too).
Now you don't have to worry about CORS or having to run everything via a local Nginx and use rewrite rules to route the /api/* queries.
2 回答779 阅读
1 回答1.1k 阅读
323 阅读
大概是这样
你在
packge.json
加入然后你页面中的请求
fetch('/api/userdata/')
就会转发到proxy
中的地址也就是真实的请求是
http://news-at.zhihu.com/api/userdata/
,而且也不会有跨域问题因为在浏览器看来,你只是发了
fetch('/api/userdata/')
,没有跨域问题