axios使用初涉

看vue的时候,vue2.0推荐使用axios做http请求,今天就学一下axios基本使用。

 

安装 axios

推荐npm方法(npm是node.js环境下的包管理器):

npm install axios  

非常任性,只推荐这一种安装方法,强迫乃们使用这种便捷的方式。觉得npm慢?或者根本无回应?下面教大家更换电脑源npm。

目前接触到最多的就是淘宝npm镜像: http://npm.taobao.org/ 

镜像,我的理解是复制了一份国外源地址的代码等到自己的国内服务器,并且及时更新,这样用户去国内服务器访问即可加快访问速度。(不知道理解的对不对,欢迎指正)

 

安装淘宝镜像定制命令cnpm

$ npm install -g cnpm --registry=https://registry.npm.taobao.org  

$ cnpm install [模块名称] //安装模块

$ cnpm sync connect //同步模块

//支持npm除了publish之外的所有命令

so,第一步的安装axios你可以换成:

cnpm install axios

 

axios基本用法:

 axios get请求之参数写在链接里:

axios.get('http://p.haoservice.com/Utility/GetProductList?key=8682dcb1b5c5488d84c10eb1767de0c5')
          .then(function (res) {
            console.log("请求成功:"+JSON.stringify(res))
          })
          .catch(function (error) {
            console.log("请求失败:"+JSON.stringify(error))
          })

axios get请求之参数写在params里:

axios.get('http://p.haoservice.com/Utility/GetProductList',{
            params:{
                key:'8682dcb1b5c5488d84c10eb1767de0c5'
            }
        })
          .then(function (res) {
            console.log("请求成功:"+JSON.stringify(res))
          })
          .catch(function (error) {
            console.log("请求失败:"+JSON.stringify(error))
          })

axios post请求:

axios.post('http://p.haoservice.com/Utility/GetProductList',{
            key:'8682dcb1b5c5488d84c10eb1767de0c5'
        })
          .then(function (res) {
            console.log("请求成功:"+JSON.stringify(res))
          })
          .catch(function (error) {
            console.log("请求失败:"+JSON.stringify(error))
          })

axios 自己配置参数生成请求:

axios({
    method:'post',//方法
    url:'/user/12345',//地址
    data:{//参数
        firstName:'Fred',
        lastName:'Flintstone'
    }
});

多重并发请求(这个厉害):

function getUserAccount(){
    return axios.get('/user/12345');
}

function getUserPermissions(){
    return axios.get('/user/12345/permissions');
}

axios.all([getUerAccount(),getUserPermissions()])
    .then(axios.spread(function(acc,pers){ //spread方法相当于拆分数组
        //两个请求现在都完成
        console.log(acc)
console.log(pers) }));

 

axios提供的请求方式(对照上面的几个实例,config配置信息:一个对象包含key:value格式的配置参数):

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]])

 

axios提供的多重并发方法(参考上面实例):

axios.all(iterable)
axios.spread(callback)

 

axios 配置参数列表:

{
// 请求地址
url: '/user',
// 请求类型
method: 'get',
// 请根路径
baseURL: 'http://www.mt.com/api',
// 请求前的数据处理
transformRequest:[function(data){}],
// 请求后的数据处理
transformResponse: [function(data){}],
// 自定义的请求头
headers:{'x-Requested-With':'XMLHttpRequest'},
// URL查询对象
params:{ id: 12 },
// 查询对象序列化函数
paramsSerializer: function(params){ }
// request body
data: { key: 'aa'},
// 超时设置s
timeout: 1000,
// 跨域是否带Token
withCredentials: false,
// 自定义请求处理
adapter: function(resolve, reject, config){},
// 身份验证信息
auth: { uname: '', pwd: '12'},
// 响应的数据格式 json / blob /document /arraybuffer / text / stream
responseType: 'json',
 
// xsrf 设置
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
 
// 下传和下载进度回调
onUploadProgress: function(progressEvent){
Math.round( (progressEvent.loaded * 100) / progressEvent.total )
},
onDownloadProgress: function(progressEvent){},
 
// 最多转发数,用于node.js
maxRedirects: 5,
 
// 最大响应数据大小
maxContentLength: 2000,
// 自定义错误状态码范围
validateStatus: function(status){
return status >= 200 && status < 300;
},
// 用于node.js
httpAgent: new http.Agent({ keepAlive: treu }),
httpsAgent: new https.Agent({ keepAlive: true }),
 
// 用于设置跨域请求代理
proxy: {
host: '127.0.0.1',
port: 8080,
auth: {
username: 'aa',
password: '2123'
}
},
// 用于取消请求
cancelToken: new CancelToken(function(cancel){})
}

axios 响应数据:

{
  // 服务器回应的数据将被包在data{}中,这点需要注意
  data: {},
 
  // `status` is the HTTP status code from the server response
  status: 200,
 
  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',
 
  // `headers` the headers that the server responded with
  // All header names are lower cased
  headers: {},
 
  // `config` is the config that was provided to `axios` for the request
  config: {},
 
  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}

axios请求数据格式(较为关键的一点):

//axios串联js对象为JSON格式。为了发送application/x-wwww-form-urlencoded格式数据

//浏览器中使用URLSearchParams
var params = new URLSearchParams();
params.append('param1','value1');
params.append('param2','value2');
axios.post('/foo',params);
//使用qs格式化数据
var qs = require('qs');
axios.post('/foo', qs.stringify({'bar':123}));

 

更多详细用法,官方文档写的灰常灰常详细,不必乱找资料。 官网传送门: https://www.npmjs.com/package/axios

一片不错的文档翻译: https://segmentfault.com/a/1190000008470355?utm_source=tuicool&utm_medium=referral

posted @ 2018-02-07 22:09  静静是小花  阅读(631)  评论(0编辑  收藏  举报