axios

打印 上一主题 下一主题

主题 576|帖子 576|积分 1728

媒介

使用 vue 开发时,频仍使用到了 axios 这个网络请求库,这里对其做一个发起请求时携带参数方式的小结。
一、根本使用

1.1. GET 请求

注意:GET 请求无请求体,可以是可以有请求体 body 的,但是不建议带。
为什么不建议带请求体?
:::details 由文心大模子 3.5 生成
在 HTTP 协议中,GET 请求通常用于请求数据,而 POST 请求则通常用于提交数据。这是因为 GET 和 POST 请求在语义和使用上有一些不同:

  • 语义上的不同

    • GET 请求:通常用于请求数据,它的语义是“获取”或“查询”。浏览器会把 GET 请求的效果(相应体)直接展示给用户。
    • POST 请求:通常用于提交数据,它的语义是“提交”或“更新”。POST 请求的效果通常是一个操纵的效果,而不是直接展示给用户的数据。

  • 请求体的处置惩罚

    • GET 请求:虽然 GET 请求可以包含请求体(body),但大多数 HTTP 客户端和服务器在处置惩罚 GET 请求时都会忽略请求体。这是因为 GET 请求的筹划初衷就是为了从服务器获取数据,而不是提交数据。GET 请求的查询参数应该放在 URL 的查询字符串中,而不是请求体中。
    • POST 请求:POST 请求通常包含请求体,用于提交数据给服务器。服务器会处置惩罚 POST 请求的请求体来获取提交的数据。

  • 缓存和书签

    • GET 请求是幂等的和安全的,这意味着多次执行相同的 GET 请求应该得到相同的效果,并且不会改变服务器上的任何数据。因此,浏览器通常会对 GET 请求举行缓存。假如 GET 请求包含请求体,这大概会导致缓存行为不一致或不可预测。
    • 由于 GET 请求的 URL 通常会被浏览器记载在历史记载或书签中,假如 URL 中包含了敏感信息(这些信息通常应该放在请求体中),那么这些信息大概会被泄露。

  • URL 长度限制

    • 浏览器和服务器通常对 URL 的长度有肯定的限制。假如 GET 请求包含大量的数据在 URL 中(通过查询参数),这大概会导致 URL 超过长度限制。

  • 安全性

    • 将敏感信息(如密码、私钥等)放在 GET 请求的 URL 中是不安全的,因为这些信息大概会被记载在浏览器历史、服务器日志或代理缓存中。这些信息应该通过 POST 请求放在请求体中,并使用得当的加密和身份验证机制来保护。

综上所述,虽然技术上 GET 请求可以包含请求体,但出于上述原因,通常不建议在 GET 请求中包含请求体。在实际开发中,应该根据请求的性子和目标选择合适的 HTTP 方法,并遵照相应的最佳实践。
:::

1.1.1. 使用 GET 方式举行无参请求

接口
  1. @GetMapping("/get/getAll")
  2. public ResResult getAllUser(){
  3.          List<User> list = userService.list();
  4.          return ResResult.okResult(list);
  5. }
复制代码
请求
  1. axios({
  2.          url:'http://localhost:8080/get/getAll',
  3.          method:'get'
  4. }).then(res=>{
  5.          console.log(res.data.data)
  6. })
复制代码
1.1.2. 使用 GET 方式请求,参数值直接放在路径中

接口
  1. @GetMapping("/get/{id}")
  2. public ResResult getUserById(@PathVariable("id") Long id){
  3.          User user = userService.getById(id);
  4.          return ResResult.okResult(user);
  5. }
复制代码
请求
  1. axios({
  2.          url:'http://localhost:8080/get/1',
  3.          method:'get'
  4. }).then(res=>{
  5.          console.log(res.data.data)
  6. })
复制代码
1.1.3. 使用 GET 方式请求,参数拼接在路径中

拼接方式 ①
使用 ? 举行参数拼接
接口
  1. @GetMapping("/get")
  2.      public ResResult getUserByIds(@RequestParam("id") Long id){
  3.          User user = userService.getById(id);
  4.          return ResResult.okResult(user);
  5. }
复制代码
请求
  1. axios({
  2.          url:'http://localhost:8080/get?id=1',
  3.          method:'get'
  4. }).then(res=>{
  5.          console.log(res.data.data)
  6. })
复制代码
拼接方式 ②
使用 params 【单个参数】
接口
  1. @GetMapping("/get")
  2.     public ResResult getUserByIds(@RequestParam("id") Long id){
  3.         User user = userService.getById(id);
  4.         return ResResult.okResult(user);
  5. }
复制代码
请求
  1. axios({
  2.          url:'http://localhost:8080/get',
  3.          params:{
  4.                  id:'2'
  5.          },
  6.          method:'get'
  7. }).then(res=>{
  8.          console.log(res.data.data)
  9. })
复制代码
拼接方式 ③
使用 params 【多个参数】
接口
  1. @GetMapping("/get")
  2.     public ResResult getUserByIds(@RequestParam("id") Long id,@RequestParam("username") String username){
  3.         LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
  4.         wrapper.eq(User::getUsername,username);
  5.         wrapper.eq(User::getId,id);
  6.         User user = userService.getOne(wrapper);
  7.         return ResResult.okResult(user);
  8. }
复制代码
请求
  1. axios({
  2.         url:'http://localhost:8080/get',
  3.         params:{
  4.                 id:'2',
  5.                 username:'swx'
  6.         },
  7.         method:'get'
  8. }).then(res=>{
  9.         console.log(res.data.data)
  10. })
复制代码
当 POST 有参请求且是简写时,要以 JSON 格式请求
  1. axios.post('http://localhost:8080/post',"id=2&username=swx").then(res=>{
  2.         console.log(res.data.data)
  3. }).catch(err=>{
  4.         console.log('timeout')
  5.         console.log(err)
  6. })
复制代码
1.1.4. GET 请求的简写方式

无参时:
  1. axios.get('http://localhost:8080/get/getAll').then(res=>{
  2.         console.log(res.data.data)
  3. }).catch(err=>{
  4.         console.log('timeout')
  5.         console.log(err)
  6. })
复制代码
有参时:
  1. axios.get('http://localhost:8080/get',{params:{id:'2',username:'swx'}}).then(res=>{
  2.         console.log(res.data.data)
  3. }).catch(err=>{
  4.         console.log('timeout')
  5.         console.log(err)
  6. })
复制代码
1.2. POST 请求

注意:POST 请求的有参、无参请求与如上的 GET 是一样的,只不外是请求方式名换一下。
如下是 POST 请求简写与传入配置项写法时,关于请求体格式的一点区别:
接口
  1. var express = require('express')
  2. var path = require('path')
  3. var bodyParser = require('body-parser')
  4. const { json } = require('body-parser')
  5. var app = express()
  6. app.use(express.static(path.join(__dirname, 'public')))
  7. app.use(bodyParser.urlencoded({ extended: false }))
  8. app.use(bodyParser.json())
  9. app.get('/a', function(req, res) {
  10.     console.log(req.query)
  11.     res.send({ "id": 1, "name": "张三" })
  12. })
  13. app.listen(3000, function() {
  14.     console.log('app is runing...')
  15. })
复制代码
请求
写法 ①
假如使用 Axios 的 POST 请求的简写情势,必要将数据以 JSON 格式传递。
  1. axios.post('/a', {
  2.         "id": 5,
  3.         "name": "ssss"
  4. }).then(response => {
  5.         console.log('/a1', response.data)
  6. }, error => {
  7.         console.log('错误', error.message)
  8. })
复制代码
请求
写法 ②
假如将数据直接作为请求体传递,不必要将数据写成 JSON 格式。axios 会根据请求头的 Content-Type 自动处置惩罚数据格式。
  1. axios({
  2.                 method: 'POST',
  3.                 url: '/a',
  4.                 data: {
  5.                         id: 1,
  6.                         name: "张三"
  7.                 }
  8.         })
  9.         .then(response => {
  10.                 console.log('/a', response.data)
  11.                 return response.data
  12.         }, error => {
  13.                 console.log('错误', error.message)
  14.         })
复制代码
二、请求失败处置惩罚

  1. axios.get('http://localhost:8080/get',{params:{id:'2',username:'swx'}}).then(res=>{
  2.         console.log(res.data.data)
  3. }).catch(err=>{
  4.         console.log('timeout')
  5.         console.log(err)
  6. })
复制代码
三、axios 并发请求

方式 1
接口
  1. @GetMapping("/get/getAll")
  2.     public ResResult getAllUser(){
  3.         List<User> list = userService.list();
  4.         return ResResult.okResult(list);
  5.     }
  6. @GetMapping("/get/get")
  7.     public ResResult getUserByIdt(@RequestParam("id") Long id){
  8.         User user = userService.getById(id);
  9.         return ResResult.okResult(user);
  10.     }
复制代码
请求
  1. axios.all([
  2.         axios.get('http://localhost:8080/get/getAll'),
  3.         axios.get('http://localhost:8080/get/get',{params:{id:'1'}})
  4. ]).then(res=>{
  5.         //返回的是数组,请求成功返回的数组
  6.         console.log(res[0].data.data),
  7.         console.log(res[1].data.data)
  8. }).catch(err=>{
  9.         console.log(err)
  10. })
复制代码
方式 2:使用 spread 方法处置惩罚返回的数组
  1. <script>
  2.   axios
  3.     .all([
  4.       axios.get("http://localhost:8080/get/getAll"),
  5.       axios.get("http://localhost:8080/get/get", { params: { id: "1" } }),
  6.     ])
  7.     .then(
  8.       axios.spread((res1, res2) => {
  9.         console.log(res1.data.data), console.log(res2.data.data);
  10.       })
  11.     )
  12.     .catch((err) => {
  13.       console.log(err);
  14.     });
  15. </script>
复制代码
四、axios 全局配置

  1. axios.defaults.baseURL='http://localhost:8080'; //全局配置属性
  2. axios.defaults.timeout=5000; //设置超时时间
  3. //发送请求
  4. axios.get('get/getAll').then(res=>{
  5.         console.log(res.data.data)
  6. });
  7. axios.post('post/getAll').then(res=>{
  8.         console.log(res.data.data)
  9. });
复制代码
五、axios 实例

  1. //创建实例
  2. let request = axios.create({
  3.         baseURL:'http://localhost:8080',
  4.         timeout:5000
  5. });
  6. //使用实例
  7. request({
  8.         url:'get/getAll'
  9. }).then(res=>{
  10.         console.log(res.data.data)
  11. });
  12. request({
  13.         url:'post/getAll',
  14.         method:'post'
  15. }).then(res=>{
  16.         console.log(res.data.data)
  17. })
复制代码
六、axios 拦截器

axios 提供了两大类拦截器:


  • 一种是请求方向的拦截(成功的、失败的)
  • 一种是相应方向的拦截(成功的,失败的)
拦截器作用:
比如:请求之前在请求头加 token、逼迫登录
相应的时候可以举行相应的数据处置惩罚
请求拦截器
  1.     //创建实例
  2.     let request = axios.create({
  3.         baseURL:'http://localhost:8080',
  4.         timeout:5000
  5.     });
  6.     //配置axios拦截器
  7.     request.interceptors.request.use(config=>{
  8.         console.log("请求进来了...")
  9.         console.log("请求成功方向")
  10.         console.log(config.data.data)
  11.         //放行请求,这一步很重要,否则报错
  12.         return config;
  13.     },err=>{
  14.         console.log("请求进来了...")
  15.         console.log("请求失败方向")
  16.         console.log(err)
  17.     });
  18.     //如果没有创建实例,则使用以下方式
  19.     //配置axios拦截器
  20.     // axios.interceptors.request.use(config=>{
  21.     //     console.log("请求进来了...")
  22.     //     console.log("请求成功方向")
  23.     //     console.log(config)
  24.     //     //放行请求
  25.     //     return config;
  26.     // },err=>{
  27.     //     console.log("请求进来了...")
  28.     //     console.log("请求失败方向")
  29.     //     console.log(err)
  30.     // });
  31.     //使用实例
  32.     request({
  33.         url:'get/getAll'
  34.     }).then(res=>{
  35.         console.log(res.data.data)
  36.     });
复制代码
相应拦截器
  1.     //创建实例
  2.     let request = axios.create({
  3.         baseURL:'http://localhost:8080',
  4.         timeout:5000
  5.     });
  6.     //配置axios拦截器
  7.     request.interceptors.response.use(config=>{
  8.         console.log("响应进来了...")
  9.         console.log("响应成功方向")
  10.         console.log(config.data.data)
  11.         //放行响应
  12.         return config;
  13.     },err=>{
  14.         console.log("响应进来了...")
  15.         console.log("响应失败方向")
  16.         console.log(err)
  17.     });
  18.     //使用实例
  19.     request({
  20.         url:'get/getAll'
  21.     }).then(res=>{
  22.         console.log(res.data.data)
  23.     });
复制代码
七、vue 中封装 axios

封装在 request.js 中
  1. //导入axios
  2. import axios from 'axios'
  3. //创建axios实例
  4. const service = axios.create({
  5.   baseURL: 接口地址,
  6.   timeout: 5000
  7. })
  8. //请求拦截器
  9. service.interceptors.request.use(
  10.   config => {
  11.     if (store.getters.token) {
  12.       config.headers['token'] = getToken()
  13.     }
  14.     //放行请求
  15.     return config
  16.   },
  17.   error => {
  18.     console.log(error)
  19.     return Promise.reject(error)
  20.   }
  21. )
  22. //响应拦截器
  23. service.interceptors.response.use(
  24.   response => {
  25.         //返回的数据
  26.     const res = response.data
  27.     if (res.code !== 200) {
  28.       Message({
  29.         message: res.message || 'Error',
  30.         type: 'error',
  31.         duration: 5 * 1000
  32.       })
  33.       // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
  34.       if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
  35.         // to re-login
  36.         MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
  37.           confirmButtonText: 'Re-Login',
  38.           cancelButtonText: 'Cancel',
  39.           type: 'warning'
  40.         }).then(() => {
  41.           store.dispatch('user/resetToken').then(() => {
  42.             location.reload()
  43.           })
  44.         })
  45.       }
  46.       return Promise.reject(new Error(res.message || 'Error'))
  47.     } else {
  48.       return res
  49.     }
  50.   },
  51.   error => {
  52.     console.log('err' + error) // for debug
  53.     Message({
  54.       message: error.message,
  55.       type: 'error',
  56.       duration: 5 * 1000
  57.     })
  58.     return Promise.reject(error)
  59.   }
  60. )
  61. export default service
复制代码
哪个模块必要发送请求直接引入即可,将以上实例导入
比如:此模块的所有请求接口:api 下的 skuInfo.js
  1. //导入axios实例
  2. const api_name = '/admin/product/skuInfo'
  3. export default {
  4.   getPageList(page, limit, searchObj) {
  5.     return request({
  6.       url: `${api_name}/${page}/${limit}`,
  7.       method: 'get',
  8.       params: searchObj
  9.     })
  10.   },
  11.   save(role) {
  12.     return request({
  13.       url: `${api_name}/save`,
  14.       method: 'post',
  15.       data: role
  16.     })
  17.   },
  18.   //新人专享
  19.   isNewPerson(id, status) {
  20.     return request({
  21.       url: `${api_name}/isNewPerson/${id}/${status}`,
  22.       method: 'get'
  23.     })
  24.   },
  25. }
复制代码
list.vue 页面中使用
  1. //先导入
  2. import api from '@/api/product/skuInfo'
  3. api.getPageList(this.page, this.limit, this.searchObj).then(
  4.          response => {
  5.            debugger
  6.            this.list = response.data.records
  7.            this.total = response.data.total
  8.            // 数据加载并绑定成功
  9.            this.listLoading = false
  10.          }
  11.        )
  12.      }
  13. api.save(this.skuInfo).then(response => {
  14.          if (response.code) {
  15.            this.$message({
  16.              type: 'success',
  17.              message: response.message
  18.            })
  19.            this.$router.push({ path: '/product/skuInfo/list' })
  20.            this.saveBtnDisabled = false
  21.          }
  22.        })
  23. //新人专享
  24. handleNewPersonChange(index, row) {
  25.        api.isNewPerson(row.id, row.isNewPerson).then(response => {
  26.          this.$message({
  27.            type: 'info',
  28.            message: '操作成功'
  29.          })
  30.          this.fetchData()
  31.        })
  32.      }
  33.    }
复制代码
main.js 中引入使用
  1. import * as API from '@/api'
  2. Vue.prototype.$API = API
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

西河刘卡车医

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表