1. axios安装
npm install axios --save
2.axios定义
在src目录下新建utils目录,新增http-util.js文件,定义一个httpGet方法做测试
import axios from 'axios'
function httpGet(url) {
axios.get(url).then(data => {
console.log(data)
})
.catch(err => {
console.log(err)
});
}
export default httpGet
3.启动测试
注意,如果本地启动,使用axios直接访问http://baidu.com这种网站,会有跨域的问题,这里就是配置代理了。在工程根目录下新增vue.config.js文件进行配置。
# vue.config.js
module.exports = {
outputDir: "dist", //build输出目录
assetsDir: "assets", //静态资源目录(js, css, img)
lintOnSave: false, //是否开启eslint
devServer: {
open: true, //是否自动弹出浏览器页面
host: "localhost",
port: "8080",
https: false, //是否使用https协议
hotOnly: false, //是否开启热更新
proxy: {
"/api": {
target: "https://www.jianshu.com/writer#/notebooks/52257148/notes/99281154/preview", //API服务器的地址
changeOrigin: true, // 虚拟的站点需要更管origin
pathRewrite: {
//重写路径 比如'/api/aaa/ccc'重写为'/aaa/ccc'
"^/api": "",
},
},
},
},
};
以上定义了/api的代理,这里我随便拿了一个可以访问的地址(target定义),方便进行测试。
login() {
console.log('login username: ' + this.username + ', pwd: ' + this.passowrd)
sessionStorage.setItem('username', this.username)
httpGet('/api') // 测试方法
this.$router.push({path: '/dashboard'})
}
4.结果验证
![](https://img.haomeiwen.com/i10030809/bebb37dca2f39d5d.png)
![](https://img.haomeiwen.com/i10030809/b04abc319a8fa8eb.png)
5.代码下载
https://gitee.com/animal-fox_admin/learn-vue-web
branch:lesson1
网友评论