如果你的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>
再次请求数据,发现问题完美解决。