create-react-app代理仅适用于访存api,不适用于浏览器的简单获取 [英] create-react-app proxy works only with fetch api but not in simple get of the browser

查看:94
本文介绍了create-react-app代理仅适用于访存api,不适用于浏览器的简单获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用在端口3000安装程序上运行的很小的create-react-app将代理请求代理到在端口8080上运行的后端服务器。
如果我将浏览器地址栏中的 http: // localhost:3000 / api / me 我返回index.html页面,但是如果我使用访存API来获取 / api / me

I'm using pretty small create-react-app running on port 3000 setup to proxy requests to backend server running on port 8080. If I put in the browser address bar http://localhost:3000/api/me I get back the index.html page but if I use fetch API to get /api/me it try to call to by backend.

问题是我必须通过将设置cookie的后端进行身份验证,但是由于我无法访问 http:// localhost:3000 / login 我无法获取cookie。

The problem is that I have to authenticate with the backend which will set a cookie but since I can't access the login page on http://localhost:3000/login I can't get the cookie.

在另一个项目上从create-react-app弹出后,我有一个小文件可以运行带有配置的webpack-dev-server

On a different project which I've eject from create-react-app I have small file to run webpack-dev-server wih the configuration

  proxy: {
    "*": "http://localhost:9191"
  }

哪怕是代理请求,即使放在浏览器地址栏中也是如此。

which does proxy requests even when put into the browser address bar.

是否可以在create-react-app中创建这样的设置?

Is it possible to create such setup in create-react-app?

推荐答案

仔细看我nto create-react-应用程序代码揭示这是设计使然:

Closer look into create-react-app code reveal that this is by design:


对于单页应用程序,我们通常希望回退到/index.html 。
但是我们也想尊重 proxy 的API调用。
因此,如果指定了 proxy ,我们需要决定使用哪个后备。
我们使用一种启发式方法:如果请求接受的text / html,则选择/index.html。
现代浏览器在导航时在 accept 标头中包含text / html。
但是,像 fetch()这样的API调用通常不会接受text / html。
如果此启发式方法对您而言效果不佳,请不要使用代理

For single page apps, we generally want to fallback to /index.html. However we also want to respect proxy for API calls. So if proxy is specified, we need to decide which fallback to use. We use a heuristic: if request accepts text/html, we pick /index.html. Modern browsers include text/html into accept header when navigating. However API calls like fetch() won’t generally accept text/html. If this heuristic doesn’t work well for you, don’t use proxy.

在REST控制台扩展中运行 http:// localhost:3000 / api / me 的GET返回正确的结果。

Running GET of http://localhost:3000/api/me inside REST Console extension return the correct result.

进一步了解获取API和cookie 显示我必须包括参数凭据:true才能发送cookie:

Further reading about Fetch API and cookies reveal that I have to include the parameter credentials:true to send cookies:

fetch('/api/me', {
  credentials: 'include'
})

这篇关于create-react-app代理仅适用于访存api,不适用于浏览器的简单获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆