可以通過axios類似error攔截的方式攔截http request請求 這樣每次request都可以默認加上token (當然前提已經在session里存儲了你的token驗證字符串)
在main.js文件中添加 http request攔截器
import Axios from 'axios' Vue.prototype.$http = Axios Axios.defaults.baseURL = 'https://www.escook.cn:8888/api/private/v1/' // http request 攔截器 Axios.interceptors.request.use(function (config) {
// 通過攔截request請求,主動為 請求頭,追加新屬性 Authorization,等於 token 值
config.headers.Authorization = window.sessionStorage.getItem('token')
return config; }, function (error) { // 對請求錯誤做些什么 return Promise.reject(error) })
// http request 攔截器 axios.interceptors.request.use( config => { var token = sessionStorage.getItem('token'); if (token) { // 判斷是否存在token,如果存在的話,則每個http header都加上token token =sessionStorage.getItem('token')+':'; config.headers.Authorization = `Basic ${new Buffer(token).toString('base64')}`; } return config; }, err => { return Promise.reject(err); });
為什么要加":"? 這里一開始我並沒有加冒號,然后發現新加的request頁面顯示401 但是消息頭里明明加上了Authorization,細看的話發現這個token和另外幾個頁面的不同 (因為另外幾個頁面的token是那天晚上的方式通過axios直接發送的) 解碼正確的token發現是缺少冒號,具體原因不是很清楚 查看文檔似乎發現了一個合理的解釋(不知道是否正確) 文檔中寫到:
$ curl -u eyJhbGciOiJIUzI1NiIsImV4cCI6MTM4NTY2OTY1NSwiaWF0IjoxMzg1NjY5MDU1fQ.eyJpZCI6MX0.XbOEFJkhjHJ5uRINh2JA1BPzXjSohKYDRT472wGOvjc:unused -i -X GET http://127.0.0.1:5000/api/resource HTTP/1.0 200 OK Content-Type: application/json Content-Length: 30 Server: Werkzeug/0.9.4 Python/2.7.3 Date: Thu, 28 Nov 2013 20:05:08 GMT { "data": "Hello, miguel!" }