vue + express 前后台分离之跨域解决方案
首先介绍一下我的需求
- 前后台分离,前端跑了两个项目,一个是 myweb 跑在 8080 端口,另一个项目 admin 跑在了 8081 端口
- 使用 node+express 搭建了一个跑在 3000 端口的服务器
- 我们现在需要解决跨域,以及前后端 cookie 携带的问题
前端 vue 项目使用 Axios 发送请求
Axios 通过设置 `axios.defaults.withCredentials=true;` 来允许请求携带 cookie
// main.js
import axios from 'axios'
import VueAxios from 'vue-axios'
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.withCredentials=true; // 设置携带 cookie
Vue.use(VueAxios, axios)
除此之外我们还需要添加 xhrFields: { withCredentials: true },crossDomain: true,
// utils.js
let option = {
method: type,
url: BASE_API + url,
xhrFields: { withCredentials: true }, // 必须设置
crossDomain: true, // 必须设置
he