【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

目录
相关文章
|
23天前
|
JavaScript 前端开发 IDE
[译] 用 Typescript + Composition API 重构 Vue 3 组件
[译] 用 Typescript + Composition API 重构 Vue 3 组件
[译] 用 Typescript + Composition API 重构 Vue 3 组件
|
23天前
|
小程序 数据安全/隐私保护
Taro@3.x+Vue@3.x+TS开发微信小程序,网络请求封装
在 `src/http` 目录下创建 `request.ts` 文件,并配置 Taro 的网络请求方法 `Taro.request`,支持多种 HTTP 方法并处理数据加密。
Taro@3.x+Vue@3.x+TS开发微信小程序,网络请求封装
|
28天前
|
搜索推荐
实现CRM与ERP系统无缝集成,优化客户关系管理
在当今竞争激烈的市场环境中,企业要想保持领先地位,必须高效地管理客户关系并优化内部资源。CRM(客户关系管理)系统与ERP(企业资源规划)系统的无缝集成,为企业提供了一种强大的工具,以实现这一目标
50 2
|
1月前
|
JavaScript API
如何使用Vue 3和Type Script进行组件化设计
【8月更文挑战第16天】如何使用Vue 3和Type Script进行组件化设计
31 3
|
1月前
|
JavaScript API
如何使用Vue 3和Type Script进行组件化设计
【8月更文挑战第16天】如何使用Vue 3和Type Script进行组件化设计
36 1
|
1月前
|
JavaScript 前端开发 安全
解锁Vue3与TypeScript的完美搭档:getCurrentInstance带你高效打造未来前端
【8月更文挑战第21天】Vue3的getCurrentInstance方法作为Composition API的一部分,让开发者能在组件内访问实例。结合TypeScript,可通过定义组件实例类型实现更好的代码提示与类型检查,提升开发效率与代码质量。例如,定义一个带有特定属性(如myData)的组件实例类型,可以在setup中获取并安全地修改这些属性。这种方式确保了一致性和减少了运行时错误,使开发更加高效和安全。
27 0
|
1月前
|
数据挖掘 BI API
简单了解CRM与SaaS系统
本文介绍了CRM(客户关系管理系统)和SaaS(软件即服务)的概念、应用场景、两者之间的关系以及CRM接口的作用和设置流程,强调了SaaS模式为CRM系统提供了灵活、便捷、经济高效的使用方式,以及CRM接口在数据集成、自动化流程、功能扩展和数据分析方面的重要性。
44 0
|
1月前
|
JavaScript 测试技术 API
Vue 3 与 TypeScript:最佳实践详解
Vue 3 与 TypeScript:最佳实践详解
|
2天前
|
SQL 安全 算法
网络安全与信息安全:保护你的数字世界
【9月更文挑战第18天】在这个数字信息时代,网络安全和信息安全的重要性不言而喻。从网络漏洞的发现到加密技术的应用,再到安全意识的提升,每一个环节都至关重要。本文将深入探讨这些主题,并提供实用的建议和代码示例,以帮助读者更好地保护自己的数字世界。
23 11
|
1天前
|
SQL 安全 网络安全
网络安全与信息安全:关于网络安全漏洞、加密技术、安全意识等方面的知识分享
【9月更文挑战第19天】在数字化时代,网络安全和信息安全已成为我们生活中不可或缺的一部分。本文将介绍网络安全漏洞、加密技术以及安全意识等方面的知识,帮助读者更好地了解网络安全的重要性,提高自己的网络安全防护能力。
26 13

热门文章

最新文章