一、axios 简介
axios 是一个基于Promise用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:
- 从浏览器中创建
XMLHttpRequest
- 从
node.js 发出 http 请求
- 支持
Promise api
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换
JSON数据
- 客户端支持防止
CSRF/XSRF
二、axios基础
axios.request(config)
axios.get(url [,config])
axios.delete(url [,config])
axios.head(url [,config])
axios.options(url [,config])
axios.post(url [,data [,config]])
axios.put(url [,data [,config]])
axios.patch(url [,data [,config]])
三、执行 GET 请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| axios.get('/user?ID=12345') .then(function (res) { console.log(res); }) .catch(function (error) { console.log(error); });
axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
|
四、执行 POST 请求
1 2 3 4 5 6 7 8 9 10 11 12 13
| axios.post('/user', { userId:"123" },{ headers:{ token:"abc" } }) .then(function (res) { console.log(res); }) .catch(function (error) { console.log(error); });
|
五、通过配置方式发送请求
get请求是发送参数,在params中定义。而POST请求是发送request body,需要在data中定义
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 26 27
| axios({ url:"pakage.json", method:"get", params:{ userId:"123" }, headers:{ token:"http-test" } }).then(res=>{ console.log(res.data); })
axios({ url:"pakage.json", method:"post", data:{ userId:"123" }, headers:{ token:"http-test" } }).then(res=>{ console.log(res.data); })
|
六、执行多个并发请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function getUserAcount(){ return axios.get("/user/1234"); } function getUserPermissions(){ return axios.get("/user/1234/getUserPermissions"); }
axios.all([getUserAccount(),getUserPerssions()]).then(axios.spread((acct, perms) => { }))
|
七、在react的应用
组件首次“挂载”(mount)时,该方法就会执行。在组件生命周期中,该方法只会执行一次
1 2 3 4 5 6 7
| componentDidMount() { axios.get(`http://www.reddit.com/r/${this.props.subreddit}.json`) .then(res => { const posts = res.data.data.children.map(obj => obj.data); this.setState({ posts }); }); }
|
八、参考