一:get请求

axios中常见的get/delete请求,也称作query请求:

//一般发送请求是这么写(不推荐):
axios.get('/user?id=12345&name=user')
.then(function (res) {
    console.log(res);
}).catch(function (err) {
    console.log(err);
});
 
//但是为了方便全局统一调用封装的axios,我一般采用(推荐)
axios.get('/user', {  //params参数必写 , 如果没有参数传{}也可以
    params: {  
       id: 12345,
       name: user
    }
})
.then(function (res) {
    console.log(res);
})
.catch(function (err) {
    console.log(err);
});


 
二:post/put/patch请求

传参方式大致用的有3种
(1) ‘Content-Type’= ‘multipart/form-data’
传参格式为 formData
(全局请求头:‘Content-Type’= ‘application/x-www-form-urlencoded’)
(request的Header:‘Content-Type’= ‘multipart/form-data’)

var formData=new FormData();
formData.append('user',123456);
formData.append('pass',12345678);
 
axios.post("/notice",formData)
     .then((res) => {return res})
     .catch((err) => {return err})


 
(2) ‘Content-Type’= ‘application/x-www-form-urlencoded’
传参格式为 query 形式,使用$qs.stringify
(全局请求头:‘Content-Type’= ‘application/x-www-form-urlencoded’)
(request的Header:‘Content-Type’= ‘application/x-www-form-urlencoded’)

import axios from 'axios'
import qs from 'Qs'
let data = {"code":"1234","name":"yyyy"};
axios.post(`${this.$url}/test/testRequest`,qs.stringify({
    data
}))
.then(res=>{
    console.log('res=>',res);            
})


 
(3) ‘Content-Type’= 'application/json
传参格式为 raw (JSON格式)
(全局请求头:‘Content-Type’= ‘application/x-www-form-urlencoded’)
(request的Header:‘Content-Type’= ‘application/json;charset=UTF-8’)

//方法一:
import axios from 'axios'
let data = {"code":"1234","name":"yyyy"};
axios.post(`${this.$url}/test/testRequest`,data)
.then(res=>{
    console.log('res=>',res);            
})
 
//方法二:
var readyData=JSON.stringify({
    id:1234,
    name:user
});
axios.post("/notice",readyData)
     .then((res) => {return res})
     .catch((err) => {return err})

————————————————
版权声明:本文为CSDN博主「海 洋️️」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_59237016/article/details/124053822

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐