前端前端学习基地

Axios传参的三种方式

2020-03-02  本文已影响0人  青争小台

开发过程中,经常需要全局设置,许多前端开发时容易忽略请求头的配置,常用的请求头有2种:

axios.defaults.timeout = 15000;  //超时响应
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; // 配置请求头(推荐)
// axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'; // 配置请求头
axios.defaults.baseURL = $core.use('http'); //确认协议和地址
axios.defaults.withCredentials = true;   // axios 默认不发送cookie,需要全局设置true发送cookie

一: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})
image.png
(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);            
})
image.png
(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})
image.png
上一篇下一篇

猜你喜欢

热点阅读