【Vue】Vue專案搭建常用的配置檔案,request.js和vue.config.js
阿新 • • 發佈:2021-07-17
request.js用來請求資料,封裝的程式碼如下:
import axios from 'axios' const request = axios.create({ timeout: 5000 }) // request 攔截器 // 可以自請求傳送前對請求做一些處理 // 比如統一加token,對請求引數統一加密 request.interceptors.request.use(config => { config.headers['Content-Type'] = 'application/json;charset=utf-8'; // config.headers['token'] = user.token; // 設定請求頭 return config }, error => { return Promise.reject(error) }); // response 攔截器 // 可以在介面響應後統一處理結果 request.interceptors.response.use( response => { let res = response.data; // 如果是返回的檔案 if (response.config.responseType === 'blob') { return res } // 相容服務端返回的字串資料 if (typeof res === 'string') { res = res ? JSON.parse(res) : res } return res; }, error => { console.log('err' + error) // for debug return Promise.reject(error) } ) export default request
vue.config.js:
// 跨域配置 module.exports = { devServer: { //記住,別寫錯了devServer//設定本地預設埠 選填 port: 9876, proxy: { //設定代理,必須填 '/api': { //設定攔截器 攔截器格式 斜槓+攔截器名字,名字可以自己定 target: 'http://localhost:9999', //代理的目標地址 changeOrigin: true, //是否設定同源,輸入是的 pathRewrite: { //路徑重寫 '/api': '' //選擇忽略攔截器裡面的單詞 } } } } }