天天看點

axios實作RESTful請求規範

  • 一般格式

axios.get(url[, config])

axios.delete(url[, config])

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

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

get和delete的格式類似,post、put、patch格式類似

  • GET:擷取資料

    後端将參數當做url 參數 接收

this.axios.get('/url/user', {
    params: {
        "name": "kevin",
        "password": "123456"
    }
})
 .then((response)=> {
    console.log(response)
})
.catch((error)=> {
    console.log(error);
});           

後端用query接收參數,URL格式:"/url/user?name=kevin&password=123456"

  • POST:新增資料

    使用post方法時header['content-type']預設為application/json

this.axios.post('/url/add', {
          "username": this.userinfo.username,
          "password": this.userinfo.password
    })
    .then((response) => {
        console.log(response);
    })
    .catch((error) => {
        console.log(error);
    });           

後端接收用JSON接收參數,URL不會展現變化

如果修改為application/x-www-form-urlencoded,那麼需要引入qs.stringify序列化

this.axios.post('url/add', this.qs.stringify({
          "username": this.userinfo.username,
          "password": this.userinfo.password
        }), {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    })
    .then((response) => {
        console.log(response);
    })
    .catch((error) => {
        console.log(error);
    });           

後端使用FORM接收參數

  • PUT:更新資料

    PUT和POST類似

this.axios.put('/url/update', {
    "userId": this.userinfo.Id,
    "userName": this.userinfo.username
})
.then((response)=> {
    console.log(response)    
})
.catch((error)=> {
    console.log(error);
});           

後端接收方式也類似

  • DELETE:删除資料

    使用delete方法時,由于資料包中沒有預設的header['content-type']=application/json,此時資料向後端傳輸時,需要做一層data封裝.

this.axios.delete('/url/delete', { 
    data: { username : "admin" , password : "123" } 
})
.then((response)=> {
    console.log(response)                   
})
.catch((error)=> {
    console.log(error);
});           

後端接收用JSON接收參數

或者後端将參數當做url 參數 接收

this.axios.delete('/url/delete', { 
    params: { username : "admin" , password : "123" } 
})
.then((response)=> {
    console.log(response)                   
})
.catch((error)=> {
    console.log(error);
});           

後端用query接收參數, URL格式:"/url/delete?name=admin&password=123"

this.axios.delete('/url/delete/' + id)
.then((response)=> {
    console.log(response)                   
})
.catch((error)=> {
    console.log(error);
});           

後端用param接收參數, URL格式:"/url/delete/id"