如果你需要这个来进行开发,并且想从你的 react 应用程序中访问一个 api,但遇到这样的错误-
Failed to load http://localhost:8180/tables:
The 'Access-Control-Allow-Origin' header has a value 'http://localhost:8180'
that is not equal to the supplied origin. Origin 'http://localhost:3000' is
therefore not allowed access. Have the server send the header with a valid
value, or, if an opaque response serves your needs, set the request's mode to
'no-cors' to fetch the resource with CORS disabled.
然后你可以很容易地让 create-react-app 服务器将你的请求代理到你的 api 服务器。
create-react-app 使用 webpack 开发服务器为您的 react 应用程序提供服务。
因此,如果您的 React 应用程序由 http://localhost:3000 提供服务,并且您要连接的 api 位于 http://localhost:8180/tables,您可以简单地将 proxy 值添加到您的 React 应用程序的 package.json 文件中,如下所示-
proxy: "http://localhost:8180",
然后从你的 react 应用调用你的 api
fetch('/tables').then(....)
请求将被发送到 create-react-app 服务器,该服务器会将其发送到 api 服务器并为您返回结果。
这里有完整的细节Proxying API Requests in Development