首页 > 其他 > 详细

vue---进行post和get请求

时间:2021-08-15 23:01:37      阅读:28      评论:0      收藏:0      [点我收藏+]

参考文档:

https://www.jb51.net/article/125717.htm

使用axios

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

基本使用方法:

get请求:

技术分享图片
// Make a request for a user with a given ID
axios.get(‘/user?ID=12345‘)
 .then(function (response) {
  console.log(response);
 })
 .catch(function (error) {
  console.log(error);
 });
 
// Optionally the request above could also be done as
axios.get(‘/user‘, {
  params: {
   ID: 12345
  }
 })
 .then(function (response) {
  console.log(response);
 })
 .catch(function (error) {
  console.log(error);
 });
 
技术分享图片

Post请求:

技术分享图片
axios.post(‘/user‘, {
 firstName: ‘Fred‘,
 lastName: ‘Flintstone‘
})
.then(function (response) {
 console.log(response);
})
.catch(function (error) {
 console.log(error);
});
技术分享图片

简单示例:

技术分享图片
// 在进行 post 和 get 请求的时候,使用 axios 进行访问
// 进行 get 请求
axios.get(url).then(function (response){
    console.log(response);
}).catch(function(error){
    console.log(error);
});
// 进行post 请求            
axios.post(url,{firstName:‘Fred‘,lastName:‘Flintstone‘}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});
技术分享图片

 这样发送请求,虽然是可以发送,但是携带的参数,是一个json字符串,会出现问题。所以我们在用post发送请求的时候,需要这样:

技术分享图片
axios({  
    method:‘post‘,  
    url:url,  
    data:{title:this.title,content:this.content},  
    headers:{‘Content-Type‘: ‘application/x-www-form-urlencoded‘},  
    transformRequest: function(obj) {  
        var str = [];  
        for(var p in obj){  
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));  
        }  
        return str.join("&");  
    }  
}).then((res)=>{
    console.log(res.data);
});
技术分享图片

技术分享图片

 上面这种只能提交一些简单的数据,对于复杂的数据,可以考虑使用 QS 对数据进行处理。

使用方法,如果找不到QS文件,可以只用 npm 安装:

npm install qs

技术分享图片

下载这个文件之后,使用 script 标签正常引入即可。

使用方法:

var formData = Qs.stringify({imgIds: [48,49],});
axios.post(url,Qs.stringify(this.formData)).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

或者是:

技术分享图片
axios({
    method: ‘post‘,
    url:url,
    data:Qs.stringify(this.formData),
}).then((res)=>{
    console.log(res);
});

vue---进行post和get请求

原文:https://www.cnblogs.com/bruce1992/p/15144684.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!