基於axios配置封裝一個簡單的request 請求


 
npm install axios
 
文件 request.js
 
import axios from "axios"
import config from './config'  

 

axios.defaults.timeout = 20 * 1000
axios.interceptors.request.use(config => {
let token = window.localStorage.getItem("token")    // 登錄所需token
if (token) {
config.headers["Authorization"] = `Bearer ${token}`
config.headers["key"] = value
}
return config
})

 

// http response 攔截器
axios.interceptors.response.use(response => {
return response
})

 

function formatUrl(newApi, optUrl = '') {
let old_domain = 'http://question-bank.ieltsbro.com'
let url = newApi ? config.pre_domain : old_domain
let isStitch = optUrl.toString().indexOf('http'); 
let newUrl = isStitch < 0 ? url + optUrl : optUrl;
return newUrl;
}

 

//忽略這幾個 status: 請求資源不存在時拋出錯誤  eg:
const skipStatus = [0, 700384, 700381, 20037, 20039, 20030];  
export default function request(options) {
let { url, method = 'GET', params, headers = {}, data = {}, newApi, ...rest } = options;
url = formatUrl(newApi, url);
headers = headers || {};
return axios({
url: url,
method: method,
params: { ...params },
headers: { ...headers },
data: data,
...rest,
})
.then(response => {
//status 非 0 的處理, error {message: 后台/http錯誤提示, response: {data: 后台返回, status: http 狀態} }
const { status, message } = response.data
if (!skipStatus.includes(status)){
const error = new Error(message)
error.response = response
throw error
}
return { ...response.data }
}).catch(error => {
throw error;
})
}
 
文件 services.js
用法:
import { request } from "request.js"
export function getData(params) {
return request({
  url: "apiUrl",
  newApi: true,
  method: "get",
  params: params 
})
}
 
export function postData(params) {
return request({
  url: "apiUrl",
  newApi: true,
  method: "post",
    data: params 
})
}
 
 
 
 
 
 
 
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM