解決vue專案axios每次請求session不一致的問題
阿新 • • 發佈:2020-10-26
1、vue開發後臺管理專案,登入後,請求資料每次session都不一致,後臺返回未登入,處理方法開啟main.js設定:
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' require('es6-promise').polyfill() import MintUI from 'mint-ui' import 'mint-ui/lib/style.css' import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; import store from './store' import axios from 'axios' // 1、在這裡引入axios axios.interceptors.response.use(function(res) { var res = res.data; if(res.status === 403 ) { router.push('/') return res; } return res; },function(error) { return Promise.reject(error); }); axios.defaults.withCredentials = true; //意思是攜帶cookie資訊,保持session的一致性 Vue.prototype.$axios = axios Vue.prototype.stringify = require('qs').stringify; Vue.use(MintUI) Vue.use(ElementUI); Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app',router,store,components: { App },template: '<App/>' })
withCredentials為false意思是不攜帶cookie資訊,為保持session的一致性需設定為true;
2、為解決跨域,需要代理
3、資料請求
補充知識:解決跨域造成Vue-element每次請求sessionID不同問題
vue-element作為前端開發框架,前後端分離專案ajax跨域,每次http請求後sessionId均會發生變化,導致獲取session失敗,
只需要在檔案vue-element-admin-master-1\src\utils\request.js中新增如下程式碼即可:
withCredentials: true,
crossDomain: true
整個axios請求為:
const service = axios.create({ baseURL: process.env.BASE_API,// api的base_url timeout: 5000,// request timeout withCredentials: true,crossDomain: true })
以上這篇解決vue專案axios每次請求session不一致的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。