create-react-app问题:关于package.json中的proxy设置

create-react-app中有个proxy设置,看介绍好像是代理的意思,可以解决cros跨域的问题,但是设置好像没有起什么作用,还是有跨域问题,不知道有没有人用过?
阅读 28.2k
6 个回答

大概是这样

你在packge.json加入

"proxy": "http://news-at.zhihu.com"

然后你页面中的请求fetch('/api/userdata/')就会转发到proxy中的地址

也就是真实的请求是http://news-at.zhihu.com/api/userdata/,而且也不会有跨域问题

因为在浏览器看来,你只是发了fetch('/api/userdata/'),没有跨域问题

刚刚也遇到这个问题,想在项目中调用天气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");

才可以。
这个一般用于开发环境中配置代理服务器,用来模拟数据什么的。

@theWalker

这个方式确实可以,只是看到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.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进