vue封装axios
建立src/apis/http.js
import axios from 'axios'; // console.log('index.html引入 public下静态文件js,配置接口地址',URLCONFIG); const instance = axios.create({ baseURL: URLCONFIG.IPConfig, timeOut: 5000 }) // console.log(instance); //post 请求需要加请求头 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; // 请求头带东西 // var name = window.sessionStorage.getItem('name'); // var josName = window.sessionStorage.getItem('jobName'); // 请求拦截器 instance.interceptors.request.use(res => { var jobId = window.sessionStorage.getItem('jobId'); var uid = window.sessionStorage.getItem('uid'); var model = window.sessionStorage.getItem('model') if (uid) { res.headers.uid = uid; // res.headers.name = name; // res.headers.josName = josName; res.headers.jobId = jobId; res.headers.model = model } return res }, (err) => { return Promise.reject(err) }) // // 响应拦截器 // instance.interceptors.request.use((response) => { // return response.data; // }, (err) => { // return Promise.reject(err); // }) /** * 使用es6的export default导出了一个函数,导出的函数代替axios去帮我们请求数据, * 函数的参数及返回值如下: * @param {String} method 请求的方法:get、post、delete、put * @param {String} url 请求的url: * @param {Object} data 请求的参数 * @returns {Promise} 返回一个promise对象,其实就相当于axios请求数据的返回值 */ export default (method, url, data = null) => { method = method.toLowerCase(); switch (method) { case 'post': return instance.post(url, data); break; case 'get': return instance.get(url, { params: data }); break; case 'delete': return instance.delete(url, { params: data }); break; case 'put': return instance.put(url, data); break; default: // console.log('未知的method--' + method) return false; } }
src同级目录 public/config.js
const URLCONFIG ={ //http请求地址 IPConfig:'http://127.0.0.1:3000', }
vue2中index.html文件中引入
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
<script src="<%= BASE_URL %>config.js" charset="utf-8"></script>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
使用:http.js同级目录创建js文件
import req from './http.js' //定义接口 export const getData = params => req('get', '/posts', params)