返回> 网站首页 

springboot跨域访问

yoours2021-07-01 21:57:17 阅读 1938

简介一边听听音乐,一边写写文章。

一、跨域访问

        只实现了cookie跨域访问

二、拦截器

public class CorsInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)

            throws Exception {

        crossDomain(request, response);

        return true;

    }


    public void crossDomain(HttpServletRequest request, HttpServletResponse response) {

        response.setHeader("Access-Control-Allow-Origin", "http://soskp.com,http://www.soskp.com,http://wx.soskp.com");

        response.setHeader("Access-Control-Allow-Methods", "POST,GET");

        response.setHeader("Access-Control-Max-Age", "3600");

        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");

        // 如果要把Cookie发到服务器,需要指定Access-Control-Allow-Credentials字段为true

        response.setHeader("Access-Control-Allow-Credentials", "true");

        response.setHeader("Access-Control-Expose-Headers", "*");

    }

}

三、注册拦截器
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CorsInterceptor()).addPathPatterns("/**");
    }
}

四、cookies
        cookie的读写见 CookieUtils.java 文件
        将token写入cookie实现跨域访问

微信小程序扫码登陆

文章评论

1938人参与,0条评论