axios 封装使用 #面向request.js
1.Vue安装:
npm install axios
2.面向request.js请求:
request.js
import axios from "axios"; //axios框架可简写为,因为axios本身就返回Promise,上面的方式只不过多穿了件相同的衣服罢了 export function request(config){ //axios封装 const instance=axios.create({ //baseConfig baseURL: 'http://localhost:92', timeout: 5000 }) //拦截器 instance.interceptors.request.use(config => { // console.log("[[[-->请求处理"); // console.log(config); // console.log("-->给请求"); return config; },error => { console.log(error) }) instance.interceptors.response.use(config => { // console.log("-->得到响应"); // console.log(config); // console.log("-->给响应]]]"); return config.data; },error => { console.log(error) }) return instance(config) }
3.使用示例
request.js使用示例:
import {request} from "network/request"; export function fileUp(upUrl,yourFile) { return request({ url: upUrl, method: 'post', headers: {'Content-Type': 'multipart/form-data'}, data:yourFile }) } /* 使用示例: // 图片上传回调函数 images_upload_handler: function (blobInfo, success, failure){ console.log("图片上传"); let formData = new FormData() formData.append('img',blobInfo.blob()) fileUp('/user/imgUp/',formData).then(response =>{ if(response['code']==20000){ success(response.data['filePath']) }else{ failure('上传失败!') } }) } */ //get请求 export function get_Request(r_Url,yourObjParam) { return request({ url: r_Url, method: 'get', params: yourObjParam }) } //post请求 export function post_Request(r_Url,yourObjdata) { return request({ url: r_Url, method: 'post', data: yourObjdata }) }