Axios使用体验

后端

只做测试用,简单写了个处理,其实也没做什么处理,收到了直接返回success。不过好久没写node了。。全都忘光光了。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//login.js
let express = require('express');
let router = express.Router();
router.get('/',function(request,response,next){
//todo 登陆处理
response.send({
code: 2000,
responseText: 'success'
});
});
module.exports = router;


//app.js
//解决下跨域
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://127.0.0.1:8080");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
let loginRouter = require('./routes/login');
app.use('/login',loginRouter);

前端

引入axios

1
2
3
4
5
npm install axios

//main.js
import axios from 'axios'
Vue.prototype.$http = axios;

做下简单的解析:

我们用$开头的属性来存放引入的库,这种写法不是强制的,只是为了提醒开发者。($on , $mount)。

Vue.prototype.$http = axios这一句用来修改Vue的原型属性。

vue+elementui

1
2
3
4
5
6
7
8
9
10
submitForm: function(formName){
this.fullscreenLoading = true; //缓冲框参数
this.$http.get(prefix + '/login').then(success=>{ //使用重写过的http
this.fullscreenLoading = false;
this.$router.push('manager');
},fail=>{
this.fullscreenLoading = false;
alert(fail);
})
}

效果

登陆

image.png

回复报文

image.png

全局配置axios

可以配置的东西很多我这里配置了全局的baseURL这样不用每一个都写一遍 http://localhost:3000

1
2
3
4
5
6
7
8
9
//Vue.prototype.$http = axios;

Vue.prototype.$http = axios.create({
baseURL: 'http://localhost:3000'
});

//直接执行下面的代码
this.$http.get('/login')
//查看console中的network,请求正常:http://localhost:3000/login