https://blog.csdn.net/lovePaul77/article/details/85681404
ajax+springboot解决跨域问题,以下报的错误就是html跨域的问题
Access to XMLHttpRequest at 'http://localhost:8080/user/login1' from origin 'http://localhost:59033' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
springboot解决跨域的问题的两种方法
前端测试代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="form-div">
<form id="form1">
<p>用户名:<input name="email" type="text" id="txtUserName" tabindex="1" size="15" value="" /></p>
<p>密 码:<input name="password" type="text" id="TextBox2" tabindex="2" size="16" value="" /></p>
<p><input type="button" value="登录" οnclick="login()"> <input type="reset" value="重置"></p>
</form>
</div>
</body>
<script type="text/javascript" src="../static/jquery/jquery-3.3.1.js"></script>
<script type="text/javascript">
function login() {
$.ajax({
//几个参数需要注意一下
type: "POST", //方法类型
dataType: "json", //预期服务器返回的数据类型
url: "http://localhost:8080/user/login1", //url
data: $('#form1').serialize(),
success: function(result) {
console.log(result); //打印服务端返回的数据(调试用)
if(200 == result.resultCode) {
alert("SUCCESS");
};
},
error: function() {
alert("异常!");
}
});
}
</script>
</html>
第一种:写一个class,配置的class
package com.example.demo;
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;
/**
* Author:Yangjingcheng
* Date:2018/
*/
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 配置所有请求
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
第二种,在你要访问的Controller的方法上面加上注解
@CrossOrigin
例子:
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.List;
@Controller
public class TestController {
@CrossOrigin
@RequestMapping("/user/login1")
@ResponseBody
public List<User> userLogin(User user) {
System.out.println(user);
ArrayList<User> users = new ArrayList<>();
for (int i = 0; i < 3; i++) {
users.add(user);
}
return users;
}
}
这样的话就会解决前端接收不到返回值得情况了