0
点赞
收藏
分享

微信扫一扫

Axios传参的三种方式

一: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})

举报

相关推荐

0 条评论