elementui-admin 跨域并携带cookie

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

                       elementui-admin 跨域并携带cookie_第1张图片

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

                elementui-admin 跨域并携带cookie_第2张图片   

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() {
    }
}

 

你可能感兴趣的:(vue,java,vue,elementui-admin,admin)