学习目标:

Axios API

学习内容:

学习  Axios API  相关知识

学习笔记:

Axios API


一、发送 post 请求

axios(config)
// 发送 POST 请求
axios({
method: ‘post’,
url: ‘/sys/user/123’,
data: {
deviceName: ‘aaa’,
}
});

二、发送 get 请求

(1)、axios(config)
// 获取远端图片
axios({
method:‘get’,
url:‘http://’,
responseType:‘stream’
})
.then(function(response) {
response.data.pipe(fs.createWriteStream(‘aaa.jpg’))
});

this.$axios({
url: url,
method: “get”,
responseType: “blob”,
params: this.dataForm,
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error);
});

(2)、axios(url[, config])

// 发送 GET 请求(默认的方法)
axios(’/sys/user/123’);


官网中显示:为方便起见,为所有支持的请求方法提供了别名,当然,在使用别名方法时, url、method、data 这些属性都不必在配置中指定。

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

注意:在使用别名方法时, url、method、data 这些属性都不必在配置中指定。

axios 请求方法的别名含义

axios.request(参数)
请求指定页面,相当于axios(参数)

axios.get(路径,参数)

请求指定页面信息,并返回实体主体,用于获取数据。

axios.delete(路径,参数)

请求服务器删除指定的页面

axios.head(路径,参数)

与 get 请求类似,但是返回的响应中没有具体的内容,用于获取报头(请求头)

axios.options(路径,参数)
允许客户端查看服务器的性能

axios.post(路径,参数)

向指定资源提交数据进行处理请求,我们在提交表单或上传文件时会用到,数据被包含在请求体中。
注:(post 请求可能会导致新的资源建立或旧的资源(已存在的资源)的修改。)用于提交数据(新建)、包括表单提交及文件上传。

axios.put(路径,参数)

从客户端向服务器传送的数据取代指定的文档的内容,用于更新数据(修改),将所有数据都推送到后端。

axios.patch(路径,参数)

回显服务器收到的请求,主要用于测试或诊断,用于更新数据(修改),只将修改的数据推送到后端。

注意:在使用别名方法时, 路径及参数都不是必需在配置中指定。

举例:
(1)、axios.request(config):

axios.request({
  
    url:"/sys/dept",
  
    method:"get",
      
    data:{type:1,page:20},
   
 })
.then(function(res){ 
     console.log(res)
  
  })
.catch(error=>{
   console.log(error)
})

request的参数:

url 定义路径

method http请求方式( post 或 get )
data 传给后台的变量

headers:{Content-Type:‘application/json’} 自定义请求头
params:{type:1,page:20} 发送数据

timeout:1000 指定请求超时的毫秒数

withCredentials:true 跨域请求是否需要凭证

responseType:‘json’ 服务器返回的数据类型
(数据类型:json,ArrayBuffer,blob,document,text,stream)

responseEncoding:“utf8” 响应字符集

**注:**
**1.post方法header 自定义请求头设置**:

 *post方式:*

 let {userId,token} ={}
  userId = userId?userId:'';token = token?token:''
  axios.post(url, data,{headers: {userId,token}})


*get方式:*

let {userId,token} = {};
userId = userId?userId:'';token = token?token:''
 axios.get(this.getUrl(url), {params:data,headers: {userId,token}})

(2)、axios.get(url [config])

this.$axios.get('/judge/info/'+this.dataForm.applyId).then(res => {
        this.deviceDate = res 
        //this.search({"relationTable":"assets_apply","relationId":this.dataForm.applyId,"type":0})
      }).catch(() => {})


 this.$axios.get(url,{responseType: 'blob'}).then(response=>{
            this.download(response);
      }).catch(error=>{
            console.log(error);
      })

(3)、axios.delete(url [config])

let data = {
      id: 1
    }
写法一
    // delete请求--- 将请求参数拼接在url上
    axios.delete('/delete', {	
      params: {	
        id: 1
      }
    }).then(res => {
      console.log(res)
    })

写法二
 // delete请求---将请求参数放在请求体
    axios.delete('/delete', {	
      data: {	
        id: 1
      }
    }).then(res => {
      console.log(res)
    })


 // delete请求--- 将请求参数拼接在url上
// delete请求---将请求参数放在请求体
    axios({
      method: 'delete',
      url: '/delete',
      params: {}, // 请求参数拼接在url上
      data: {}  // 请求参数放在请求体
    }).then(res => {
      console.log(res)
    })

(4)、axios.head(url [config])

HTTP请求头限制这几种字段:Accept、Accept-Language、Content-Language、Content-Type、Last-Event-ID

(5)axios.options(url [config])
HTTP 的 OPTIONS 方法 用于获取目的资源所支持的通信选项。
客户端可以对特定的 URL 使用 OPTIONS 方法。

实际上,出于安全考虑,并不是所有域名访问后端服务都可以。
其实在正式跨域之前,浏览器会根据需要发起一次预检(也就是option请求),用来让服务端返回允许的方法(如get、post),被跨域访问的Origin(来源或者域),还有是否需要Credentials(认证信息)等。

浏览器发送预检请求的原因及情形?

1.发送预检请求的原因
问题的根源,在于,我们发出去的请求,不是"simple request", 那么在每次发送之前,都要自动发出一个option请求。
原因:
浏览器将CORS请求分为两类:简单请求(simple request)和非简单请求(not-simple-request),简单请求浏览器不会预检,而非简单请求会预检。
对于简单请求,浏览器直接请求,会在请求头信息中,增加一个origin字段,来说明本次请求来自哪个源(协议+域名+端口)。
服务器根据这个值,来决定是否同意该请求,服务器返回的响应会多几个头信息字段。

1.Access-Control-Allow-Origin:该字段是必须的,* 表示接受任意域名的请求,还可以指定域名

2.Access-Control-Allow-Credentials:该字段可选,是个布尔值,表示是否可以携带cookie,
(注意:如果Access-Control-Allow-Origin字段设置*,此字段设为true无效)

3.Access-Control-Allow-Headers:该字段可选,里面可以获取Cache-Control、Content-Type、Expires等, 如果想要拿到其他字段,就可以在这个字段中指定。

2.简单请求的规则及排查方式

**

1.请求方式只能是:GET、POST、HEAD
2.HTTP请求头限制这几种字段:Accept、Accept-Language、Content-Language、Content-Type、Last-Event-ID
3.Content-type只能取:application/x-www-form-urlencoded、multipart/form-data、text/plain

**

(6)axios.post(url [ data[ config]])

1)applicition/json请求方式

//写法一      
          
  this.$axios.post('/base/ruletype/list',
        { 'name': this.filterText }).then(res => {
        this.menuList = res
      })

 //写法二
            axios({
                method: 'post',//请求方法
                data: data,
                url: '后台接口地址',
            }).then(res => {
                //执行成功后代码处理
            })

2)formData请求方式

//写法一
            let data = {
                id:1
            }
            let formData = new formData()
            for(let key in data){
                fromData.append(key,data[key])
            }
            axios.post('接口地址', fromData}).then(
                (res) => {
                    //执行成功后代码处理
                }
            )
//写法二
            axios({
                method: 'post',//请求方法
                data: fromData,
                url: '后台接口地址',
            }).then(res => {
                //执行成功后代码处理
            })

(7)、axios.put(url [data[config]])

//写法一
            let data = {
                id:1
            }
            axios.put('接口地址', data}).then(
                (res) => {
                    //执行成功后代码处理
                }
            )
//写法二
axios({
    method:"put",   //请求方法
    url:"http://localhost:8090/sys/dept",  //后台接口地址
    data:{"action":"refreshToken"},
    headers:{
        "Authorization":"Bearer " + oldToken
    }
}).then(res => {
                //执行成功后代码处理
    })

(8)、axios.patch(url [ data[ config]])

//写法一
            let data = {
                id:1
            }
            axios.patch('接口地址', data}).then(
                (res) => {
                    //执行成功后代码处理
                }
            )
//写法二
            axios({
                method: 'patch',      //请求方法
                data: data,
                url: 'http://localhost:8090/sys/dept',  //后台接口地址
            }).then(res => {
                //执行成功后代码处理
            })
axios  涉及到的知识还有很多,在此记录自己今天的学习内容。