springBoot配置跨域

1.配置跨域有两种方式

1.在每个controller中设置

 @ResponseBody
    @RequestMapping(value = "/cs", method = RequestMethod.POST)
    public String cs(HttpServletResponse response, HttpServletRequest request) {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");// 允许服务器向浏览器跨域响应时更改浏览器(客户端)的cookie
        
        return "跨域测试";
    }

这种方式只能确保这一个controller中可以跨域

2.新建一个配置类WebMvcConfig配置全局的跨域

import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfig  extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS","TRACE")
                .allowCredentials(true);
    }
}
  • registry.allowedOrigins(““)设置跨域访问的域名,如果是,默认都可以访问。
  • registry.allowCredentials(true)设置是否允许客户端发送cookie信息。默认是false,但是如果不接受cookie,则会导致客户端获取的session不同这种问题

2.前端访问

如果前端发送ajax请求保证同一个会话中session相同,则需设置 withCredentials: true

  $.ajax({
                url: "http://localhost:9001/loginOut",
                // data: data,
                dataType: "json",
                type: "get",
                // async: false, //此处必须要有这句话,否则任然会传值失败
                //加上这句话,允许浏览器向服务器跨域请求时携带cookie
                //加上这句话,允许浏览器向服务器跨域请求时携带cookie
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                success: function(data) {
                    console.log(data)
                },
                error: function() {
                    alert("token认证失败")
                }
            });
        })
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZNineSun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值