前端ajax请求跨域设置
ajax请求里加上xhrFields: { withCredentials: true },crossDomain: true
例如:
<script>
jQuery(document).ready(function () {
$("#getotp").on("click", function () {
var telphone = $("#telphone").val();
if (telphone == null || telphone == "") {
alert("手机号不能为空");
//避免传递到上一层form-post处理
return false;
}
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded",
url: "http://localhost:8090/user/getotp",
data: {
"telphone": $("#telphone").val(),
},
xhrFields: { withCredentials: true },
crossDomain: true,
success: function (data) {
if (data.status == "success") {[添加链接描述](https://blog.csdn.net/crippty/article/details/80179356)
alert("otp验证码已经发送到了您的手机上请注意查收");
window.location.href="register.html"
} else {
alert("otp验证码发送失败,原因为:" + data.data.errMsg);
}
},
error: function (data) {
alert("otp发送失败,原因为:" + data.responseText);
},
});
return false;
})
});
</script>
Spring Boot后端跨域设置多种方式
1. 使用CrossOrigin注解(局部跨域配置)
- 将CrossOrigin注解加在Controller层的方法上,该方法定义的RequestMapping端点将支持跨域访问
- 将CrossOrigin注解加在Controller层的类定义处,整个类所有的方法对应的RequestMapping端点都将支持跨域访问
例如:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller("goods")
@CrossOrigin(allowCredentials = "true",allowedHeaders = "*")
public class GoodsController {
@GetMapping("goods-url")
public Response queryGoodsWithGoodsUrl(@RequestParam String goodsUrl) throws Exception {}
}
2. 使用HttpServletResponse设置响应头(全局跨域配置)
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "CorsFilter ")
@Configuration
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
}
3. 重写WebMvcConfigurer的addCorsMappings方法(全局跨域配置)
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.context.annotation.Bean;
@Configuration
public class GlobalCorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") //添加映射路径,“/**”表示对所有的路径实行全局跨域访问权限的设置
.allowedOrigins("*") //开放哪些ip、端口、域名的访问权限
.allowCredentials(true) //是否允许发送Cookie信息
.allowedMethods("GET","POST", "PUT", "DELETE") //开放哪些Http方法,允许跨域访问
.allowedHeaders("*") //允许HTTP请求中的携带哪些Header信息
.exposedHeaders("*"); //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
}
};
}
}
4. 使用CorsFilter进行全局跨域配置
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 GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
//开放哪些ip、端口、域名的访问权限,星号表示开放所有域
config.addAllowedOrigin("*");
//是否允许发送Cookie信息
config.setAllowCredentials(true);
//开放哪些Http方法,允许跨域访问
config.addAllowedMethod("GET","POST", "PUT", "DELETE");
//允许HTTP请求中的携带哪些Header信息
config.addAllowedHeader("*");
//暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
config.addExposedHeader("*");
//添加映射路径,“/**”表示对所有的路径实行全局跨域访问权限的设置
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
}
参考
1. 前端跨域设置 withCredentials: true
2. 详解SpringBoot应用跨域访问解决方案
3. Springboot2.0解决跨域问题