发表于: 2019-10-29 22:57:14

1 666


今天完成的事情:


今天一直在搞这个请求的事情,之前在任务六的登陆页面中发送的是get请求,但是这个要换成post请求,所以一直在网上找这个vue的post请求,但是还是没找到标准的答案,写的实在是太多了:

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); });


明天计划的事情:


明天继续写请求。

收获:


心态比较崩,没想到在这个问题上面搞这么久,在网上找的又不一样,不知道到底怎么写,明天再请教一下师兄。



返回列表 返回列表
评论

    分享到