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

如果你的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文件中加入以下的依赖:


   com.thetransactioncompany
   cors-filter
   2.5

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


    CORS
    com.thetransactioncompany.cors.CORSFilter
    
      cors.allowOrigin
      *
    
    
      cors.supportedMethods
      GET, POST, HEAD, PUT, DELETE
    
    
      cors.supportedHeaders
      Accept, Origin, X-Requested-With, Content-Type, Last-Modified
    
    
      cors.exposedHeaders
      Set-Cookie
    
    
      cors.supportsCredentials
      true
    


    CORS
    /*

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

你可能感兴趣的:(React,React笔记)