springboot配置跨域请求CorsConfig

springboot配置跨域请求CorsConfig

feign创建config包
包下创建CorsConfig类
在类中配置开启跨域请求:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 将跨域请求写在类中
 * @Configuration 声明这是一个配置类
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {
     

    static final String ORIGINS[] = new String[] {
     "GET","DELETE","POST","PUT","OPTIONS"};

    /**
     * addCorsMappings
     * 在cors的注册器上 声明哪些请求可以跨域方法
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
     
        registry.addMapping("/**")
                //运行哪些请求类型 跨域方法
                //OPTIONS 预检请求 在访问跨域方法之前 浏览器对跨域的资源会发送一个
                //OPTIONS请求 测试一下当前方法是否支持跨域
                .allowedMethods(ORIGINS)
                //Origin 允许远程访问的域名
                //*代表所有ip都可以方法 在测试时可以使用此配置
                .allowedOrigins("*")
                //是否允许当前请求跨域携带cookie
                .allowCredentials(true)
                //OPTIONS请求 存活时间
                .maxAge(3600);
    }
}

ajax发起跨域请求:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
	<script src="https://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<script>
	/*$(function(){
        $.ajax({
            url:"http://localhost:8082/shop/findShopDeptListByPid/1",
            type:"GET",
            //data:JSON.stringify({'productId':'ds5df4gf','productPrice':500,'productDesc':'测试跨域能够成功'}),
            dataType:"json",
            //contentType: "application/json",
            success:function(data){
                alert(data);
            },error:function(){
                alert("未知错误");
            }
        })
    })*/
	
	
	$(function(){
     
		$.ajax({
     
		   url:"http://localhost:8082/store/addStore",
		   type:"POST",
		   data:JSON.stringify({
     "storeLogo":"测试店铺logo","storeCover":"测试店铺封面","storeName":"测试店铺名称","industryClassification":1,"storeDefaultDiscountRatio":6.6,"phoneNumber":"测试手机号","businessLicense":"测试营业执照","nameOfLicense":"测试执照名称","licenseRegistrationNo":"测试执照注册号","provinceCode":1,"cityCode":11,"areaCode":111,"validityOfLicenseStartTime":"2020-06-15","validityOfLicenseEndTime":"2020-06-25"}),
		   dataType:"json",
		   contentType: "application/json",
		   success:function(data){
     
		      alert(data);
		   },error:function(){
     
		      alert("未知错误");
		   }
		})
	})
</script>
</body>
</html>

你可能感兴趣的:(Java,spring,boot,全局跨域配置,spring,java)