【Vue3+TypeScript】CRM系统项目搭建之 — Axiox 网络请求封装(一)

简介: 【Vue3+TypeScript】CRM系统项目搭建之 — Axiox 网络请求封装(一)

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


一、基本使用

1.1. GET 请求

注意:GET请求无请求体,可以是可以有请求体body的,但是不建议带。

为什么不建议带请求体?

:::details 由文心大模型 3.5 生成

在HTTP协议中,GET请求通常用于请求数据,而POST请求则通常用于提交数据。这是因为GET和POST请求在语义和使用上有一些不同:

  1. 语义上的不同
  • GET请求:通常用于请求数据,它的语义是“获取”或“查询”。浏览器会把GET请求的结果(响应体)直接展示给用户。
  • POST请求:通常用于提交数据,它的语义是“提交”或“更新”。POST请求的结果通常是一个操作的结果,而不是直接展示给用户的数据。
  1. 请求体的处理:
  • GET请求:虽然GET请求可以包含请求体(body),但大多数HTTP客户端和服务器在处理GET请求时都会忽略请求体。这是因为GET请求的设计初衷就是为了从服务器获取数据,而不是提交数据。GET请求的查询参数应该放在URL的查询字符串中,而不是请求体中。
  • POST请求:POST请求通常包含请求体,用于提交数据给服务器。服务器会处理POST请求的请求体来获取提交的数据。
  1. 缓存和书签
  • GET请求是幂等的和安全的,这意味着多次执行相同的GET请求应该得到相同的结果,并且不会改变服务器上的任何数据。因此,浏览器通常会对GET请求进行缓存。如果GET请求包含请求体,这可能会导致缓存行为不一致或不可预测。
  • 由于GET请求的URL通常会被浏览器记录在历史记录或书签中,如果URL中包含了敏感信息(这些信息通常应该放在请求体中),那么这些信息可能会被泄露。
  1. URL长度限制:
  • 浏览器和服务器通常对URL的长度有一定的限制。如果GET请求包含大量的数据在URL中(通过查询参数),这可能会导致URL超过长度限制。
  1. 安全性
  • 将敏感信息(如密码、私钥等)放在GET请求的URL中是不安全的,因为这些信息可能会被记录在浏览器历史、服务器日志或代理缓存中。这些信息应该通过POST请求放在请求体中,并使用适当的加密和身份验证机制来保护。


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

:::


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

接口

 @GetMapping("/get/getAll")
 public ResResult getAllUser(){
   List<User> list = userService.list();
   return ResResult.okResult(list);
 }

请求

 axios({
   url:'http://localhost:8080/get/getAll',
   method:'get'
 }).then(res=>{
   console.log(res.data.data)
 })
1.1.2. 使用 GET 方式请求,参数值直接放在路径中

接口

 @GetMapping("/get/{id}")
 public ResResult getUserById(@PathVariable("id") Long id){
         User user = userService.getById(id);
         return ResResult.okResult(user);
 }

请求

 axios({
   url:'http://localhost:8080/get/1',
   method:'get'
 }).then(res=>{
   console.log(res.data.data)
 })
1.1.3. 使用 GET 方式请求,参数拼接在路径中

拼接方式 ①

使用 ? 进行参数拼接

接口

 @GetMapping("/get")
     public ResResult getUserByIds(@RequestParam("id") Long id){
         User user = userService.getById(id);
         return ResResult.okResult(user);
 }

请求

 axios({
   url:'http://localhost:8080/get?id=1',
   method:'get'
 }).then(res=>{
   console.log(res.data.data)
 })

拼接方式 ②

使用 params 【单个参数】

接口

@GetMapping("/get")
    public ResResult getUserByIds(@RequestParam("id") Long id){
        User user = userService.getById(id);
        return ResResult.okResult(user);
}

请求

 axios({
   url:'http://localhost:8080/get',
   params:{
     id:'2'
   },
   method:'get'
 }).then(res=>{
   console.log(res.data.data)
 })

拼接方式 ③

使用 params 【多个参数】

接口

@GetMapping("/get")
    public ResResult getUserByIds(@RequestParam("id") Long id,@RequestParam("username") String username){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,username);
        wrapper.eq(User::getId,id);
        User user = userService.getOne(wrapper);
        return ResResult.okResult(user);
 }

请求

axios({
  url:'http://localhost:8080/get',
  params:{
    id:'2',
    username:'swx'
  },
  method:'get'
}).then(res=>{
  console.log(res.data.data)
})

当 POST 有参请求且是简写时,要以 JSON 格式请求

axios.post('http://localhost:8080/post',"id=2&username=swx").then(res=>{
  console.log(res.data.data)
}).catch(err=>{
  console.log('timeout')
  console.log(err)
})
1.1.4. GET 请求的简写方式

无参时:

axios.get('http://localhost:8080/get/getAll').then(res=>{
  console.log(res.data.data)
}).catch(err=>{
  console.log('timeout')
  console.log(err)
})

有参时:

axios.get('http://localhost:8080/get',{params:{id:'2',username:'swx'}}).then(res=>{
  console.log(res.data.data)
}).catch(err=>{
  console.log('timeout')
  console.log(err)
})

1.2. POST 请求

注意:POST 请求的有参、无参请求与如上的 GET 是一样的,只不过是请求方式名换一下。

如下是 POST 请求简写与传入配置项写法时,关于请求体格式的一点区别:

接口

var express = require('express')
var path = require('path')
var bodyParser = require('body-parser')
const { json } = require('body-parser')
var app = express()


app.use(express.static(path.join(__dirname, 'public')))

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())


app.get('/a', function(req, res) {
    console.log(req.query)
    res.send({ "id": 1, "name": "张三" })
})



app.listen(3000, function() {
    console.log('app is runing...')
})

请求

写法 ①

如果使用 Axios 的 POST 请求的简写形式,需要将数据以 JSON 格式传递。

axios.post('/a', {
  "id": 5,
  "name": "ssss"
}).then(response => {
  console.log('/a1', response.data)
}, error => {
  console.log('错误', error.message)
})

请求

写法 ②

如果将数据直接作为请求体传递,不需要将数据写成JSON格式。axios会根据请求头的Content-Type自动处理数据格式。

axios({
    method: 'POST',
    url: '/a',
    data: {
      id: 1,
      name: "张三"
    }
  })
  .then(response => {
    console.log('/a', response.data)
    return response.data
  }, error => {
    console.log('错误', error.message)
  })


二、请求失败处理

axios.get('http://localhost:8080/get',{params:{id:'2',username:'swx'}}).then(res=>{
  console.log(res.data.data)
}).catch(err=>{
  console.log('timeout')
  console.log(err)
})


三、axios 并发请求

方式 1

接口

@GetMapping("/get/getAll")
    public ResResult getAllUser(){
        List<User> list = userService.list();
        return ResResult.okResult(list);
    }

@GetMapping("/get/get")
    public ResResult getUserByIdt(@RequestParam("id") Long id){
        User user = userService.getById(id);
        return ResResult.okResult(user);
    }

请求

axios.all([
  axios.get('http://localhost:8080/get/getAll'),
  axios.get('http://localhost:8080/get/get',{params:{id:'1'}})
]).then(res=>{
  //返回的是数组,请求成功返回的数组
  console.log(res[0].data.data),
  console.log(res[1].data.data)
}).catch(err=>{
  console.log(err)
})

方式2:使用spread方法处理返回的数组

<script>
    axios.all([
        axios.get('http://localhost:8080/get/getAll'),
        axios.get('http://localhost:8080/get/get',{params:{id:'1'}})
    ]).then(
        axios.spread((res1,res2)=>{
            console.log(res1.data.data),
            console.log(res2.data.data)
        })
    ).catch(err=>{
        console.log(err)
    })
</script>


四、axios全局配置

axios.defaults.baseURL='http://localhost:8080'; //全局配置属性
axios.defaults.timeout=5000; //设置超时时间

//发送请求
axios.get('get/getAll').then(res=>{
  console.log(res.data.data)
});

axios.post('post/getAll').then(res=>{
  console.log(res.data.data)
});


五、axios实例

//创建实例
let request = axios.create({
  baseURL:'http://localhost:8080',
  timeout:5000
});
//使用实例
request({
  url:'get/getAll'
}).then(res=>{
  console.log(res.data.data)
});

request({
  url:'post/getAll',
  method:'post'
}).then(res=>{
  console.log(res.data.data)
})


【Vue3+TypeScript】CRM系统项目搭建之 — Axiox 网络请求封装(二):https://developer.aliyun.com/article/1556821

目录
相关文章
|
11天前
|
JavaScript 前端开发 开发工具
TypeScript的介绍,let age:number = xxx,可以直接看出数据类型,Type由微软开发,可以在任何浏览器和系统中运行,比较适合大型项目,TypeScript的安装
TypeScript的介绍,let age:number = xxx,可以直接看出数据类型,Type由微软开发,可以在任何浏览器和系统中运行,比较适合大型项目,TypeScript的安装
|
8天前
|
数据采集 存储 搜索推荐
CRM客户系统全解析:定义与企业应用
Zoho CRM是一个集成客户数据、销售流程、市场活动和客户服务的平台,助力企业提升效率和竞争力。它支持销售管理、客户细分及个性化营销,改善客户体验。系统在销售预测、客户档案管理和市场营销策略制定上发挥作用。然而,挑战包括系统集成、数据质量、员工培训和用户接纳。企业需克服这些挑战以确保CRM的有效运营。
15 2
|
13天前
|
存储 JavaScript 开发者
【Vue3+TypeScript】CRM系统项目搭建之 — 关于 VUE3 语法新变化(四)
【Vue3+TypeScript】CRM系统项目搭建之 — 关于 VUE3 语法新变化(四)
14 0
【Vue3+TypeScript】CRM系统项目搭建之 — 关于 VUE3 语法新变化(四)
|
13天前
|
JavaScript API 网络架构
【Vue3+TypeScript】CRM系统项目搭建之 — 关于 VUE3 语法新变化(三)
【Vue3+TypeScript】CRM系统项目搭建之 — 关于 VUE3 语法新变化(三)
7 0
【Vue3+TypeScript】CRM系统项目搭建之 — 关于 VUE3 语法新变化(三)
|
13天前
|
JavaScript API
【Vue3+TypeScript】CRM系统项目搭建之 — 关于 VUE3 语法新变化(二)
【Vue3+TypeScript】CRM系统项目搭建之 — 关于 VUE3 语法新变化(二)
14 0
【Vue3+TypeScript】CRM系统项目搭建之 — 关于 VUE3 语法新变化(二)
|
13天前
|
JavaScript API UED
【Vue3+TypeScript】CRM系统项目搭建之 — 关于 VUE3 语法新变化(五)
【Vue3+TypeScript】CRM系统项目搭建之 — 关于 VUE3 语法新变化(五)
13 0
|
1月前
|
网络协议 算法 Linux
【嵌入式软件工程师面经】Linux网络编程Socket
【嵌入式软件工程师面经】Linux网络编程Socket
48 1
|
3天前
|
Linux
linux网络统计信息和端口占用情况基本语法
linux网络统计信息和端口占用情况基本语法
|
10天前
|
网络协议 安全 Ubuntu
7 个有用的免费 Linux 网络隧道
【7月更文挑战第4天】
46 0
7 个有用的免费 Linux 网络隧道
|
23天前
|
安全 物联网 Linux
学习Linux对网络安全的重要性
**学习Linux对网络安全至关重要:** 1. 开源操作系统广泛应用于服务器、网络设备,掌握Linux是安全专家必备技能。 2. Linux内置安全特性,如最小权限和防火墙,加上丰富的安全工具,提供强大保障。 3. 可定制性允许灵活配置,满足安全需求,开源社区提供持续更新和教育资源。 4. 学习Linux能提升攻防能力,用于系统加固和渗透测试,适应跨平台安全场景。 5. 随着云计算和物联网发展,Linux在网络安全中的角色日益关键。
47 3