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);
    }
    }
發佈了5 篇原創文章 · 獲贊 1 · 訪問量 797
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章