1.在src下新建util文件夹,在util下新建request.js文件:
封装axios:
import axios from 'axios'import QS from 'qs';// import store from '@/store/index.js';import { Message } from 'element-ui'; //element库的消息提示,可以不用// 环境的切换// if (process.env.NODE_ENV == 'development') { //开发// axios.defaults.baseURL = '/api';}// else if (process.env.NODE_ENV == 'debug') { //测试// axios.defaults.baseURL = 'https://www.ceshi.com';// }// else if (process.env.NODE_ENV == 'production') { //线上// axios.defaults.baseURL = 'https://www.production.com';// }// 请求超时时间axios.defaults.timeout = 15000;// post请求头axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';// 请求拦截器axios.interceptors.request.use( config => { // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了 const token = '45f8f587-7b46-462f-a8c4-1ca4dc64a336'; if (token) { // 判断是否存在token,如果存在的话,则每个http header都加上token config.headers.Token = token; } return config; }, error => { return Promise.error(error); });// 响应拦截器axios.interceptors.response.use( response => { if (response.status === 200) { return Promise.resolve(response); } else { return Promise.reject(response); } }, // 服务器状态码不是200的情况 error => { if (error.response.status) { console.log(error) } return Promise.reject(error.response); });export function get(url, params) { return new Promise((resolve, reject) => { axios.get(url, { params: params }) .then(res => { resolve(res.data); }) .catch(err => { if (!err.response) { Message({ showClose: true, message: 'get请求错误', type: 'error' }); } else { reject(err.data); console.log(err.response, '异常2'); } }) });}export function post(url, params) { return new Promise((resolve, reject) => { axios.post(url, params) .then(res => { resolve(res.data); }) .catch(err => { if (!err.response) { Message({ showClose: true, message: 'post请求错误', type: 'error' }); } else { reject(err.data); console.log(err.response, '异常2'); } }) });}export default axios
2:在util文件下再新建api.js文件:
import { get, post } from './request'export function getTest(params) { return post(`/api/tbk/dg_optimus_material`, params);}export function getNvZhuang(params) { return post(`/api/tbk/dg_material_optional `, params);}
3:在html页面访问接口:
import { getTest, getNvZhuang } from "@/util/api.js"; // 导入api接口 mounted: function() { this.queryList(); }, methods: { //精选 queryList() { let params = { pageNo: 1, pageSize: 20 }; getTest(params) .then(res => { this.jingxuanlist = res.tbk_dg_optimus_material_response.result_list.map_data; console.log(this.jingxuanlist); }) .catch(error => { console.log(error); }); }}