React跨域问题

React应用跨域问题解决方案

最近在开发React项目的时候用到fetch发起http请求,却报出了如下错误:
fetch TypeError: Failed to fetch
或者遇到

Access to fetch at 'http://localhost:8088/api/*****' from origin 'http://localhost:3001' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is 
present on the requested resource. If an opaque response serves your needs, 
set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

这两种状况出现原因都可能是没有解决跨域问题,解决方案如下:

方案一、配置代理服务

package.json文件中,添加如下参数
"proxy": "http://localhost:8088"
启动proxy参数值为服务器域名

方案二、应用http-proxy-middleware(HTTP代理中间件)

参考博文:react使用 http-proxy-middleware解决跨域问题

你可能感兴趣的:(React)