SpringBoot和Vue前后分离解决axios跨域问题详解程序员

SpringBoot和Vue前后分离解决axios跨域问题
前端
proxyTable: {

‘/api’: { //将www.exaple.com印射为/apis
target: ‘https://www.example.com, // 接口域名
secure: true, // 如果是https接口,需要配置这个参数
changeOrigin: true, //是否跨域
pathRewrite: { // 如果接口本身没有api的路径,那么这里将发送到后端的请求重写为没有api的路径
‘^/api’: ‘/’
}
}
}
如果axios封装 添加如下配置
import axios from ‘axios’
axios.defaults.withCredentials = true

后端配置 2选1

  1. 局部配置(必须在控制器上面配置)
    可以配置在控制器的类上
    @CrossOrigin(origins = {“http://localhost:8081”, “null”}) //http://localhost:8081 前端网址
    public class ShopController {

    }
    或者控制器的方法里面
    @CrossOrigin(origins = {“http://localhost:8081”, “null”}) //http://localhost:8081 前端网址
    public String UserController {

    }
    2.全局配置
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    final HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader(“Access-Control-Allow-Origin”, “http://localhost:3000”);
    response.setHeader(“Access-Control-Allow-Credentials”, “true”);
    response.setHeader(“Access-Control-Allow-Methods”, “POST, PUT, GET, DELETE”);
    response.setHeader(“Access-Control-Allow-Headers”, “Origin, Connection, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, User-Lang, User-Agent, Authorization”);
    response.setHeader(“Access-Control-Max-Age”, “3600”);
    if (“OPTIONS”.equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {

    response.setStatus(HttpServletResponse.SC_OK);
    } else {

    chain.doFilter(req, res);
    }
    }

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/1730.html

(0)
上一篇 2021年7月15日
下一篇 2021年7月15日

相关推荐

发表回复

登录后才能评论