elementui-admin 跨域并携带cookie

标签: vue  java

1、下载完elementui-admin模板之后,找到utils文件目录下的 api.js 文件

                       

2、在创建axios实例下面添加一行代码 ,如图所示

                   

service.defaults.withCredentials = true

   添加过后,前端配置完成 。

3、修改相对应后台的跨域请求

   后端需要设置Access-Control-Allow-Origin(值为项目的前台地址,例如: http://ip),

   并且设置header('Access-Control-Allow-Credentials: true')

   后端代码奉上:

package com.cmbird.config;

import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域
 * @author zyj
 * @date 2019-12-12 17:32:42
 */
@Component
public class CorsFilter implements Filter {

    final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class);

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        // todo 修改服务器IP 不然跨域无法获取 cookie
        response.setHeader("Access-Control-Allow-Origin", "http://ip");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}

 

版权声明:本文为qq_31807569原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_31807569/article/details/103513062