vue项目中引入axios及使用
一,下载依赖
$ npm install axios --save
二,引入依赖并全局注册
import axios from ‘axios’
Vue.prototype.$axios = axios
//全局注册,使用方法为:this.$axios
三,配置config文件
(1) ,通过webpack初始化的项目
在config文件夹中的index.js文件内修改如下:
dev: {
env: require('./dev.env'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://localhost:3000/api/',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
host: '192.168.3.xxx',//IP地址
port: 8080,
autoOpenBrowser: true,
errorOverlay: true,
notifyOnErrors: true,
poll: false,
cacheBusting: true,
cssSourceMap: false
}
(2) ,通过webpack-simple初始化的项目
在根目录下webpack.config.js文件中修改如下:
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true,
host: "192.168.3.xxx",//端口号
port: 8080,
proxy: {
'/api/*': {
target: 'http://localhost:3000',//跨域要访问的地址及端口
changeOrigin: true,
secure: false,
}
}
}
四,使用并发送get请求
//以下代码也可以封装在函数中,在其他地方调用
this.$axios.get('/api/fillePath/apiPort', {
params: {
ID: 12345 //可选
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
五,使用并发送post请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
参考链接:
https://www.cnblogs.com/silent007/p/8603367.html
https://github.com/axios/axios