1、先描述问题,出现一下问题
(1) No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin
(2) {jqXHR: {…}, textStatus: "parsererror", errorThrown: Error: jQuery18308951892757595779_1529915874976 was not called
2、项目代码说明
a) springboot项目,controller接口如下:
@RequestMapping(value = "/getUserByAge", method = RequestMethod.GET)
@ResponseBody
public Result findByUserAge(@RequestParam(value = "userAge", required = true) int userAge) {
System.out.println("开始查询...");
return userService.findUserByAge(userAge);
}
b) web工程的ajax如下:
var requestData = {
userAge: 30
};
page.ajax(page.getAjaxSettings({
serviceType: "defaultCall",
url: "http://localhost:8081/api/user/getUserByAge",
data: requestData,
success: function (resultData) {
if (resultData.status != page.FWResultStatus.Success || resultData.data == null) {
gridVue.$Message.error('数据获取失败!');
return;
};
var response = resultData.data;
gridVue.gridData.data = response.datas;
if (response.paging.pageIndex == "0") {
gridVue.gridData.pageIndex = gridVue.gridData.pageIndex;
} else {
gridVue.gridData.pageIndex = response.paging.pageIndex;
};
gridVue.gridData.totalPage = response.paging.totalPage;
gridVue.gridData.totalRecord = response.paging.totalRecord;
$.myDoThing.addEllipsisTitleHtml();
},
error: function(){
console.info(111);
},
complete: function () {
gridVue.isShowLoading = false;
}
}));
3、ajax请求出现问题
浏览器调用结果为:Failed to load http://localhost/api/user/getUserByAge?userAge=30&_=1529915977699: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8087' is therefore not allowed access.
4、问题分析及解决
分析:由于该请求已经跨域(springboot项目端口为8080,tomcat中启动的web项目端口为8087),所以请求成功,network中,response结果为:{"useTime":0.0,"status":"Success","data":{"id":1,"name":"AASSD","age":20},"infoList":[],"sqlInfoList":[],"errorMsgList":null},但是ajax直接进error。
解决方法尝试:
(1)将ajax请求中dataType设置为"jsonp"格式,所以请求成功,network中,response结果为:{"useTime":0.0,"status":"Success","data":{"id":1,"name":"AASSD","age":20},"infoList":[],"sqlInfoList":[],"errorMsgList":null},但是ajax直接进error。
提示json格式错误,所以不能用jsonp
(2)改造后台接口
Spring Boot提倡基于Java的配置,@Configuration
百度得知:
尽管你可以使用一个XML源来调用 SpringApplication.run() ,我们通常建议你使用 @Configuration 类作为主要源。一般定义 main 方法的类也是主要 @Configuration 的一个很好候选。你不需要将所有的 @Configuration 放进一个单独的类。 @Import 注解可以用来导入其他配置类。另外,你也可以使用 @ComponentScan 注解自动收集所有的Spring组件,包括 @Configuration 类。如果你绝对需要使用基于XML的配置,我们建议你仍旧从一个 @Configuration 类开始。你可以使用附加的 @ImportResource 注解加载XML配置文件。@Configuration注解该类,等价 与XML中配置beans;用@Bean标注方法等价于XML中配置bean
在这里,我是添加一个类,如下:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}
再启动springboot项目,将web项目的ajax的请求的dataType改回json格式,调成功!