vue axios 发送get请求传递参数给后端失败_26. Axios

24816852436a4d8842f042af46f6d26f.png

重点:

重点当然是学会使用 Axios 发送 get 和 post 请求啦~~

准备工作

首先,我们安装 Axios:

npm install axios

然后在项目中引入(哪个组件用到 Axios 就在哪个组件引入):

import axios from 'axios'

可是如果所有组件都要使用 Axios,难道我要在所有组件都引入一次吗?

不用,我们只要将 Axios 全局挂载到 Vue 原型上:

Vue.prototype.$http = axios  // $http 是随便起的名字,你也可以使用其他名字

使用 Axios 发送 get 请求

向 Vue中文社区 发送请求(API 可以在 官网提供的 API 找到):

getData () {
  this.$http.get('https://www.vue-js.com/api/v1/topics')
    .then((response) => {
      console.log(response)
    })
    .catch((error) => {
      console.log(error)
    })
}

因为 Axios 是基于 Promise 的,所以可以使用 then 和 catch 。

在发送请求时,还可以传递参数,参数的传递有两种方式:

第一种:对象

getData () {
  this.$http.get('https://www.vue-js.com/api/v1/topics, {
    params: {
      page: 1,  // 页码
      limit: 20  // 每页显示的数量
    }
  }')
    .then((response) => {
      console.log(response)
    })
    .catch((error) => {
      console.log(error)
    })
}

第二种:类似于查询字符串

getData () {
  this.$http.get('https://www.vue-js.com/api/v1/topics?page=1&limit=20')
    .then((response) => {
      console.log(response)
    })
    .catch((error) => {
      console.log(error)
    })
}

推荐使用第一种方式,因为它修改方便,也更直观。

使用 Axios 发送 post 请求

post 传递数据有两种格式:

  • form­-data 格式,类似于:?page=1&limit=20
  • x-­www-­form-­urlencoded 格式,类似于:{page: 1, limit: 20}

在 Axios 中,post 请求的参数必须是 form-data 格式。

postData () {
  this.$http.post(url, {
    params: {
      page: 1,
      limit: 20
    }
  })
    .then((response) => {
      console.log(response)
    })
    .catch((error) => {
      console.log(error)
    })
}

上面这种写法是不可行的,后台接收到的数据会是 x-www-form-urlencoded 格式。

这里推荐 qs 插件,使用 qs.stringify 方法,将 对象 转变成 字符串,那么后台接收到的就是 form-data 格式。

安装 qs 插件:

npm install qs

引入 qs:

import qs from 'qs'

然后将上面的 postData 方法改成:

postData () {
  this.$http.post(url, qs.stringify({
    params: {
      page: 1,
      limit: 20
    }
  }))
    .then((response) => {
      console.log(response)
    })
    .catch((error) => {
      console.log(error)
    })
}

END~~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值