【axios笔记①】post/get使用及其细节

POST传参用data,GET传参用params(POST的话可以混用)

 

POST方法:

普通post请求:conten-typet:application/x-www-form-urlencoded

带文件post/get请求:content-type:'multipart/form-data'

var post_data = new URLSearchParams();
post_data.append('a',1);
//或两种方法都可以,但如果上传文件就一定要上面那种了
var post_data = new FormData();
post_data.append('a',1);
//var file = document.querySelector('#file');
//post_data.append('file',file.files[0]);

axios({
	method:'post',
	url:'你的地址',
	data:post_data,
    //post的话可以混用get的传参
    //params:{b:2};
    // (自定头部的话跨域会报错,我也不懂为什么,jq反而一切正常)
    headers:{
        //普通请求
        'Content-Type': 'application/x-www-form-urlencoded',

        //上传文件或普通请求
        // 'Content-Type': 'multipart/form-data',

        //自定义头部
        'X-Custom-Header': '123456789132456789'
    }
}).then((data)=>{
    //输出返回数据
    console.log(data.data)
}).catch((error)=>{
    //输出错误信息
    console.log(error)
});

axios.post('你的地址',
            {
                data:post_data
            },
            {
                headers:{
                //自定义头部
                'X-Custom-Header': '123456789132456789'
                }
            }).then((data)=>{
    //输出返回数据
    console.log(data.data)
}).catch((error)=>{
    //输出错误信息
    console.log(error)
});

错误示例:(直接把json传给data中)

axios({
	method:'post',
	url:'你的地址',
	data:{
            a:1  //直接报错
        },
}).then((data)=>{
    //输出返回数据
    console.log(data.data)
});

GET方法

axios({
	method:'get',
	url:'你的地址',
    params:{b:2};
    // (自定头部的话跨域会报错,我也不懂为什么,jq反而一切正常)
    headers:{
        //上传文件或普通请求
        // 'Content-Type': 'multipart/form-data',

        //自定义头部
        'X-Custom-Header': '123456789132456789'
    }
}).then((data)=>{
    //输出返回数据
    console.log(data.data)
}).catch((error)=>{
    //输出错误信息
    console.log(error)
});

axios.get('你的地址',
            {
                params:{b:2}
            },
            {
                headers:{
                //自定义头部
                'X-Custom-Header': '123456789132456789'
                }
            }).then((data)=>{
    //输出返回数据
    console.log(data.data)
}).catch((error)=>{
    //输出错误信息
    console.log(error)
});

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值