作者 朱兆平

http部分request携带登录后得到的TOKEN与后端交互

1 import axios from 'axios' 1 import axios from 'axios'
2 import Vue from 'vue' 2 import Vue from 'vue'
3 import qs from 'qs' 3 import qs from 'qs'
4 -// let base = 'http://127.0.0.1:7003';  
5 -axios.defaults.baseURL = 'http://localhost:8082/api'; 4 +
6 Vue.prototype.$http = axios; 5 Vue.prototype.$http = axios;
7 6
8 -export const requestLogin = params => {  
9 - return axios({  
10 - method: 'POST',  
11 - url: '/login',  
12 - data: qs.stringify(params),  
13 - withCredentials: true,  
14 - //下面转换成urlencode参数,也可以用QS包处理,qs.stringify(data)  
15 - // transformRequest: [function (data) {  
16 - // // Do whatever you want to transform the data  
17 - // let ret = ''  
18 - // for (let it in data) {  
19 - // ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'  
20 - // }  
21 - // return ret  
22 - // }],  
23 - headers: {  
24 - 'Content-Type': 'application/x-www-form-urlencoded'  
25 - }  
26 - })  
27 - // return axios.post(`${base}/login`, params).then(res => res.data);  
28 -}; 7 +
29 export const getuserMenus = params => { return axios.get(`/perm/userMenus`, { params: params }); }; 8 export const getuserMenus = params => { return axios.get(`/perm/userMenus`, { params: params }); };
30 9
31 export const getUserList = params => { return axios.get(`/user/list`, { params: params }); }; 10 export const getUserList = params => { return axios.get(`/user/list`, { params: params }); };
1 import axios from 'axios' 1 import axios from 'axios'
  2 +import qs from 'qs'
  3 +
  4 +
2 axios.defaults.baseURL = 'http://localhost:8082/api'; 5 axios.defaults.baseURL = 'http://localhost:8082/api';
3 -let base = axios.defaults.baseURL+'/role';  
4 6
5 -axios.interceptors.request.use(config => {  
6 - // 这里可以加一些动作, 比如来个进度条开始动作,  
7 - return config  
8 -}, error => {  
9 - return Promise.reject(error)  
10 -});  
11 7
12 -axios.interceptors.response.use(response => response, error => Promise.resolve(error.response));  
13 8
14 export default { 9 export default {
15 post(url, data) { 10 post(url, data) {
16 return axios({ 11 return axios({
17 - method: 'post', // 请求协议 12 + method: 'POST', // 请求协议
18 url: url, // 请求的地址 13 url: url, // 请求的地址
19 - data: qs.stringify(data), // post 请求的数据 14 + data: data, // post 请求的数据
20 timeout: 30000, // 超时时间, 单位毫秒 15 timeout: 30000, // 超时时间, 单位毫秒
21 headers: { 16 headers: {
22 - 'Content-Type': 'application/json;charset=UTF-8' 17 + 'Content-Type': 'application/json;charset=UTF-8',
23 } 18 }
24 }) 19 })
25 }, 20 },
26 get(url, params) { 21 get(url, params) {
27 - return axios.get(`${base}/${url}`, { params: params }); 22 + return axios({
  23 + method: 'GET',
  24 + url: url,
  25 + data: params,
  26 + headers: {
  27 + 'Content-Type': 'application/json;charset=UTF-8',
  28 + }
  29 + });
28 }, 30 },
29 put(url, params){ 31 put(url, params){
30 return axios({ 32 return axios({
31 method: 'PUT', 33 method: 'PUT',
32 - url: `${base}/${url}`, 34 + url: url,
33 data: params, 35 data: params,
34 headers: { 36 headers: {
35 'Content-Type': 'application/json;charset=UTF-8' 37 'Content-Type': 'application/json;charset=UTF-8'
@@ -39,12 +41,23 @@ export default { @@ -39,12 +41,23 @@ export default {
39 del: (url,params) => { 41 del: (url,params) => {
40 return axios({ 42 return axios({
41 method: 'DELETE', 43 method: 'DELETE',
42 - url: `${base}/${url}`, 44 + url: url,
43 data: params, 45 data: params,
44 headers: { 46 headers: {
45 'Content-Type': 'application/json;charset=UTF-8' 47 'Content-Type': 'application/json;charset=UTF-8'
46 } 48 }
47 }) 49 })
  50 + },
  51 + login: data =>{
  52 + return axios({
  53 + method: 'POST', // 请求协议
  54 + url: '/login', // 请求的地址
  55 + data: qs.stringify(data), // post 请求的数据
  56 + timeout: 30000, // 超时时间, 单位毫秒
  57 + headers: {
  58 + 'Content-Type': 'application/x-www-form-urlencoded',
  59 + }
  60 + })
48 } 61 }
49 } 62 }
50 63
1 import axios from 'axios' 1 import axios from 'axios'
2 2
3 -axios.defaults.baseURL = 'http://localhost:8082/api';  
4 -let base = axios.defaults.baseURL+'/role'; 3 +let base = '/role';
5 4
6 5
7 export const getList = params => { return axios.get(`${base}/list`, { params: params }); }; 6 export const getList = params => { return axios.get(`${base}/list`, { params: params }); };
  1 +import http from './http.js'
  2 +let baseUrl = '/user'
  3 +
  4 +export const getUserList = params => { return http.get(`${baseUrl}/list`, params); };
  5 +
  6 +export const getUserListPage = params => { return http.get(`/user/list`,params) };
  7 +
  8 +export const removeUser = params => { return http.del(`/user/del`,params)};
  9 +
  10 +export const batchRemoveUser = params => { return http.del(`/user/batchremove`, { params: params }); };
  11 +
  12 +export const editUser = params => { return http.put(`/user/edit`,params)};
  13 +
  14 +export const addUser = params => { return http.post(`/user/add`,params)};
  15 +
  16 +export const setUserRole = params => { return http.put(`/user/roleset`,params)};
@@ -7,6 +7,7 @@ import 'element-ui/lib/theme-default/index.css' @@ -7,6 +7,7 @@ import 'element-ui/lib/theme-default/index.css'
7 import VueRouter from 'vue-router' 7 import VueRouter from 'vue-router'
8 import store from './vuex/store' 8 import store from './vuex/store'
9 import Vuex from 'vuex' 9 import Vuex from 'vuex'
  10 +import axios from 'axios'
10 //import NProgress from 'nprogress' 11 //import NProgress from 'nprogress'
11 //import 'nprogress/nprogress.css' 12 //import 'nprogress/nprogress.css'
12 import rout from './routes' 13 import rout from './routes'
@@ -18,7 +19,9 @@ Vue.filter('datefmt',function(input,fmtstring){ @@ -18,7 +19,9 @@ Vue.filter('datefmt',function(input,fmtstring){
18 19
19 return moment(input).format(fmtstring) 20 return moment(input).format(fmtstring)
20 21
21 -}) 22 +});
  23 +
  24 +
22 25
23 Mock.bootstrap(); 26 Mock.bootstrap();
24 import 'font-awesome/css/font-awesome.min.css' 27 import 'font-awesome/css/font-awesome.min.css'
@@ -42,20 +45,81 @@ router.beforeEach((to, from, next) => { @@ -42,20 +45,81 @@ router.beforeEach((to, from, next) => {
42 if (to.path == '/login') { 45 if (to.path == '/login') {
43 sessionStorage.removeItem('user'); 46 sessionStorage.removeItem('user');
44 sessionStorage.removeItem('menu'); 47 sessionStorage.removeItem('menu');
  48 + sessionStorage.removeItem('token');
45 } 49 }
46 let user = JSON.parse(sessionStorage.getItem('user')); 50 let user = JSON.parse(sessionStorage.getItem('user'));
47 - if (!user && to.path != '/login' && !sessionStorage.getItem('menu')) { 51 + if (!user && to.path != '/login' && !sessionStorage.getItem('menu') && !sessionStorage.getItem('token')) {
48 next({ path: '/login' }) 52 next({ path: '/login' })
49 } else { 53 } else {
50 next() 54 next()
51 } 55 }
52 -}) 56 +});
  57 +
  58 +axios.interceptors.response.use(
  59 + res => {
  60 + //对响应数据做些事
  61 + if (res.data && res.status===200) {
  62 + this.$message({
  63 + // 饿了么的消息弹窗组件,类似toast
  64 + showClose: true,
  65 + message: res.data.error.message.message ? res.data.error.message.message : res.data.error.message,
  66 + type: "error"
  67 + });
  68 + return Promise.reject(res.data.error.message);
  69 + }
  70 + return res;
  71 + },
  72 + error => {
  73 + // 用户登录的时候会拿到一个基础信息,比如用户名,token,过期时间戳
  74 + // 直接丢localStorage或者sessionStorage
  75 + if (!sessionStorage.getItem("token")) {
  76 + // 若是接口访问的时候没有发现有鉴权的基础信息,直接返回登录页
  77 + router.push({
  78 + path: "/login"
  79 + });
  80 + } else {
  81 +
  82 + // 下面是接口回调的satus ,因为我做了一些错误页面,所以都会指向对应的报错页面
  83 + if (error.response.status === 401) {
  84 + router.push({
  85 + path: "/login"
  86 + });
  87 + }
  88 +
  89 + // 下面是接口回调的satus ,因为我做了一些错误页面,所以都会指向对应的报错页面
  90 + if (error.response.status === 403) {
  91 + router.push({
  92 + path: "/error/403"
  93 + });
  94 + }
  95 + if (error.response.status === 500) {
  96 + router.push({
  97 + path: "/error/500"
  98 + });
  99 + }
  100 + if (error.response.status === 502) {
  101 + router.push({
  102 + path: "/error/502"
  103 + });
  104 + }
  105 + if (error.response.status === 404) {
  106 + router.push({
  107 + path: "/error/404"
  108 + });
  109 + }
  110 + }
  111 + // 返回 response 里的错误信息
  112 + let errorInfo = error.data.error ? error.data.error.message : error.data;
  113 + return Promise.reject(errorInfo);
  114 + }
  115 +);
  116 +
53 117
54 //router.afterEach(transition => { 118 //router.afterEach(transition => {
55 //NProgress.done(); 119 //NProgress.done();
56 //}); 120 //});
57 121
58 -new Vue({ 122 +let vue = new Vue({
59 //el: '#app', 123 //el: '#app',
60 //template: '<App/>', 124 //template: '<App/>',
61 router, 125 router,
@@ -32,8 +32,8 @@ @@ -32,8 +32,8 @@
32 </template> 32 </template>
33 33
34 <script> 34 <script>
35 - import { requestLogin,getuserMenus } from '../api/api';  
36 - import rt from '../routes' 35 + import axios from 'axios'
  36 + import http from '../api/http';
37 //import NProgress from 'nprogress' 37 //import NProgress from 'nprogress'
38 export default { 38 export default {
39 data() { 39 data() {
@@ -104,13 +104,12 @@ @@ -104,13 +104,12 @@
104 this.logining = true; 104 this.logining = true;
105 //NProgress.start(); 105 //NProgress.start();
106 var loginParams = {username: this.ruleForm2.account, password: this.ruleForm2.checkPass}; 106 var loginParams = {username: this.ruleForm2.account, password: this.ruleForm2.checkPass};
107 - requestLogin(loginParams).then(res => { 107 + http.login(loginParams).then(res => {
108 this.logining = false; 108 this.logining = false;
109 //NProgress.done(); 109 //NProgress.done();
110 let status = res.status; 110 let status = res.status;
111 let authentication = res.data.authentication; 111 let authentication = res.data.authentication;
112 - let user = authentication.principal;  
113 - let loginSuccess = authentication.authenticated; 112 + let loginSuccess = authentication.token;
114 let loginUserMenus = res.data.loginUserMenus; 113 let loginUserMenus = res.data.loginUserMenus;
115 if (status !== 200) { 114 if (status !== 200) {
116 let msg = "登录错误"; 115 let msg = "登录错误";
@@ -119,7 +118,11 @@ @@ -119,7 +118,11 @@
119 type: "error" 118 type: "error"
120 }); 119 });
121 } else if (loginSuccess) { 120 } else if (loginSuccess) {
122 - sessionStorage.setItem('user', JSON.stringify(user)); 121 + sessionStorage.setItem('user', JSON.stringify(authentication));
  122 + sessionStorage.setItem('token','Bearer '+ loginSuccess);
  123 + //设置token,设置axios 基本配置
  124 + let token = sessionStorage.getItem('token');
  125 + axios.defaults.headers.common['Authorization'] = token;
123 //处理用户menu 126 //处理用户menu
124 _this.userMenus = loginUserMenus.list; 127 _this.userMenus = loginUserMenus.list;
125 console.log("userMenus:"); 128 console.log("userMenus:");
@@ -56,7 +56,7 @@ @@ -56,7 +56,7 @@
56 <!--工具条--> 56 <!--工具条-->
57 <el-col :span="24" class="toolbar"> 57 <el-col :span="24" class="toolbar">
58 <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button> 58 <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
59 - <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="5" :total="total" style="float:right;"> 59 + <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total" style="float:right;">
60 </el-pagination> 60 </el-pagination>
61 </el-col> 61 </el-col>
62 62
@@ -183,7 +183,7 @@ @@ -183,7 +183,7 @@
183 <script> 183 <script>
184 import util from '../../common/js/util' 184 import util from '../../common/js/util'
185 import NProgress from 'nprogress' 185 import NProgress from 'nprogress'
186 - import { getUserList, removeUser, batchRemoveUser, editUser, addUser, setUserRole } from '../../api/api'; 186 + import { getUserList, removeUser, batchRemoveUser, editUser, addUser, setUserRole } from '../../api/user';
187 import { getList} from '../../api/role_api'; 187 import { getList} from '../../api/role_api';
188 import moment from 'moment' 188 import moment from 'moment'
189 export default { 189 export default {
@@ -265,7 +265,7 @@ @@ -265,7 +265,7 @@
265 this.getUsers(); 265 this.getUsers();
266 }, 266 },
267 //获取用户列表 267 //获取用户列表
268 - getUsers() { 268 + getUsers:function() {
269 let para = { 269 let para = {
270 pageNum: this.pageNum, 270 pageNum: this.pageNum,
271 pageSize: this.pageSize, 271 pageSize: this.pageSize,
@@ -280,9 +280,8 @@ @@ -280,9 +280,8 @@
280 //NProgress.done(); 280 //NProgress.done();
281 }).catch((error) => { 281 }).catch((error) => {
282 this.listLoading = false; 282 this.listLoading = false;
283 - let res= error.response.data;  
284 283
285 - alert(res.msg); 284 + alert(error);
286 }); 285 });
287 286
288 }, 287 },
@@ -436,7 +435,7 @@ @@ -436,7 +435,7 @@
436 }, 435 },
437 //批量删除 436 //批量删除
438 batchRemove: function () { 437 batchRemove: function () {
439 - var ids = this.sels.map(item => item.id).toString(); 438 + var ids = this.sels.map(item => item.userId).toString();
440 this.$confirm('确认删除选中记录吗?', '提示', { 439 this.$confirm('确认删除选中记录吗?', '提示', {
441 type: 'warning' 440 type: 'warning'
442 }).then(() => { 441 }).then(() => {