spring解决跨域

https://www.jianshu.com/p/abb5f6bf92c3   强烈推荐阅读至少能了解一点点原理

https://blog.csdn.net/qq_43486273/article/details/83272500

1.使用过滤器解决跨域问题

 access-control-allow-headers: Authorization, Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, X-Requested-By, If-Modified-Since, X-File-Name, X-File-Type, Cache-Control, Origin

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CORSFilter implements Filter {
    /**
     * 解决ajax跨域问题
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        String origin = req.getHeader("Origin");/*获取客户端的域名**/

        res.addHeader("Access-Control-Allow-Credentials", "true");/*允许带Cookie的跨域Ajax请求*/
        res.addHeader("Access-Control-Allow-Origin", origin); /*设置允许访问的域名地址**/
        res.addHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");/*允许请求的方式**/
        res.addHeader("Access-Control-Allow-Headers", "*");/*设置允许前端添加所有自定义请求头**/
//      res.addHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, X-Requested-By, If-Modified-Since, X-File-Name, X-File-Type, Cache-Control, Origin");

        /**
         * 设置预检命令的缓存时效。单位是"秒"
         * 如果没有失效,则不会再次发起OPTION预检请求
         */
        res.addHeader("Access-Control-Max-Age", "7200");

        if (req.getMethod().equals("OPTIONS")) {
            response.getWriter().print("");
            res.setStatus(204);
        }
        try {
            chain.doFilter(request, response);
        } catch (ServletException e) {
            int code = res.getStatus(); //获取相应状态码res.getStatus()
            JSONObject jsonData = new JSONObject();
            jsonData.put("code", code);
            jsonData.put("msg", "OPTIONS The request failed");
            jsonData.put("result", "");
            String dataStr = jsonData.toJSONString();
            response.getWriter().println("{data:" + dataStr + "}");
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}

 

 

res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN,token");/**前端可以发送token这些自定义的请求头**/

 

posted @ 2019-08-29 00:19  智走  阅读(1245)  评论(0编辑  收藏  举报