本文實例為大家分享了vue數(shù)據(jù)請求攔截的具體代碼,供大家參考,具體內(nèi)容如下
在寧武等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供成都做網(wǎng)站、成都網(wǎng)站設(shè)計 網(wǎng)站設(shè)計制作專業(yè)公司,公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站建設(shè),成都全網(wǎng)營銷推廣,外貿(mào)營銷網(wǎng)站建設(shè),寧武網(wǎng)站建設(shè)費(fèi)用合理。
在src文件夾下創(chuàng)建utils文件夾
同時在文件夾下創(chuàng)建request.js和auth.js文件
request.js為請求攔截、請求數(shù)據(jù)封裝主入口
auth.js為設(shè)置token和刪除token及判斷用戶是否登錄封裝主入口
auth.js (封裝token)
export function isLogin() { if (localStorage.getItem('token')) { return true; } else { return false; } } export function getToken() { return localStorage.getItem('token'); } export function setToken(token) { localStorage.setItem('token', token); } export function removeToken() { localStorage.removeItem('token'); }
下載axios(命令: npm install axios --save-dev)、同時引入axios、getToken
import axios from 'axios'; import { getToken } from './auth';
創(chuàng)建實例:傳兩個參數(shù)(timeout(超時時間)、baseUrl(服務(wù)器路徑))
const instance = axios.create({ timeout: 5000, baseURL: 'https://xxxxxxxxx/xxxx/', });
請求攔截
// 請求攔截 instance.interceptors.request.use( function(config) { // eslint-disable-next-line prettier/prettier config.headers.authorization = 'Bearer ' + getToken(); return config; }, function(error) { // Do something with request error return Promise.reject(error); } ); instance.interceptors.response.use( response => { return response; }, error => { if (error.response.status == 401) { window.location.href = '/#/login'; } if (error.response.status == 404) { window.location.href = '/404.html'; } return Promise.reject(error.response.data); } );
請求封裝
/** * 獲取數(shù)據(jù) get請求 * @param {*} url * @param {*} config */ export const get = (url, config) => instance.get(url, config); /** * post請求 * @param {*} url * @param {*} data * @param {*} config */ export const post = (url, data) => instance.post(url, data); /** * put * @param {*} url * @param {*} data * @param {*} config */ export const put = (url, data, config) => instance.put(url, data, config); /** * delete * @param {*} url * @param {*} config */ export const remove = (url, config) => instance.delete(url, config);
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
文章名稱:Vue實現(xiàn)數(shù)據(jù)請求攔截
網(wǎng)頁路徑:http://jinyejixie.com/article44/jjeihe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、做網(wǎng)站、網(wǎng)頁設(shè)計公司、軟件開發(fā)、小程序開發(fā)、Google
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)