在React中使用cors进行跨域异步请求。

本文详细介绍了如何在React应用中解决跨域问题,通过在前端使用fetch进行异步请求,并在后端配置CORS过滤器,实现localhost:3000与localhost:8081之间的跨域数据交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果你的React的发布的端是localhost:3000而你要请求的数据的端口发布在localhost:8081,你就要考虑到请求的跨域问题,本篇我们介绍使用cors进行跨域异步请求。我们以Javaweb项目作为数据的提供者。

第一步:在前端解决跨域问题,设置React中的fetch请求的参数:

 fetch('http://localhost:8081/ssm/user/getUserList',//跨域请求的路径
      {
        method: "GET",
        mode: "cors",
        headers: {
          'Accept': 'application/json,text/plain,*/*'
        }
      }).then(response => response.json()).then(result => { 
        // 在此处写获取数据之后的处理逻辑
         console.log(result);
         }).catch(function (e) {
            console.log("fetch fail"); 
          });
      }

在我们对fetch请求设置好以后你发现你的请求能够成功,请求的响应数据也能够在浏览器端看到,但是浏览器会报错“Access to fetch at 'http://localhost:8081/ssm/user/getUserList' from origin 'http://localhost:3000' has been blocked by CORS policy”,未解决这一问题我们还需在后端对其进行相应的处理。

第二步:在后端解决跨域问题。

在我们的pom.xml文件中加入以下的依赖:

<dependency>
   <groupId>com.thetransactioncompany</groupId>
   <artifactId>cors-filter</artifactId>
   <version>2.5</version>
</dependency>

然后在我们的web.xml文件中加入以下配置信息:

<filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    <init-param>
      <param-name>cors.allowOrigin</param-name>
      <param-value>*</param-value>
    </init-param>
    <init-param>
      <param-name>cors.supportedMethods</param-name>
      <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
    </init-param>
    <init-param>
      <param-name>cors.supportedHeaders</param-name>
      <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
    </init-param>
    <init-param>
      <param-name>cors.exposedHeaders</param-name>
      <param-value>Set-Cookie</param-value>
    </init-param>
    <init-param>
      <param-name>cors.supportsCredentials</param-name>
      <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

再次请求数据,发现问题完美解决。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值