axios 各种方式的请求 示例

news2024/9/24 21:22:50

GET请求

示例一:

  • 服务端代码
@GetMapping("/f11")
public String f11(Integer pageNum, Integer pageSize) {
    return pageNum + " : " + pageSize;
}
  • 前端代码
<template>
  <div class="home">
    <button @click="getFun1">发送get请求</button>
  </div>
</template>
<script>
  import axios from 'axios'
  export default {
    name: 'Home',
    methods: {
      getFun1 () {
        axios.get('http://localhost/blog/f11?pageNum=12&pageSize=8').then(res => {
          console.log(res)
        })
      }
    }
  }
</script>

示例二:

  • 服务端代码
@GetMapping("/f12")
public String f12(Integer pageNum, Integer pageSize, HttpServletRequest request) {
    String token = request.getHeader("token");
    return pageNum + " : " + pageSize + " : " + token;
}
  • 前端代码
<template>
  <div class="home">
    <button @click="getFun2">发送get请求</button>
  </div>
</template>
<script>
  import axios from 'axios'
  export default {
    name: 'Home',
    methods: {
      getFun2 () {
        axios.get('http://localhost/blog/f12', {
          params: {
            pageNum: 12,
            pageSize: 8
          },
          headers: {
            token: 'asdf123456'
          }
        }).then(res => {
          console.log(res)
        })
      }
    }
  }
</script>

GET方式采用接口方式携带参数,比如上面示例最终请求服务器端的url是:
在这里插入图片描述

POST请求

示例一:

  • 服务端代码
@PostMapping("/f21")
public String f21(@RequestBody String param) {
    return param;
}
  • 前端代码
<template>
  <div class="home">
    <button @click="postFun1">发送post请求</button>
  </div>
</template>
<script>
  import axios from 'axios'
  export default {
    name: 'Home',
    data () {
      return {
        queryInfo1: {
          query: {
            username: 'zhangsan',
            password: '1234'
          }
        }
      }
    },
    methods: {
      postFun1 () {
        let _this = this
        axios.post('http://localhost/blog/f21', _this.queryInfo1).then(res => {
          console.log(res)
        })
      },
    }
  }
</script>

结果:
在这里插入图片描述
在这里插入图片描述

示例二:

  • 服务端代码
@PostMapping("/f21")
public String f21(@RequestBody String param) {
    return param;
}
  • 前端代码
<template>
  <div class="home">
    <button @click="postFun2">发送post请求</button>
  </div>
</template>
<script>
  import axios from 'axios'
  export default {
    name: 'Home',
    data () {
      return {
        queryInfo2: {
          username: 'zhangsan',
          password: '1234'
        }
      }
    },
    methods: {
      postFun2 () {
        let _this = this
        axios.post('http://localhost/blog/f21', {
          data: _this.queryInfo2
        }).then(res => {
          console.log(res)
        })
      }
    }
  }
</script>

结果:
在这里插入图片描述
在这里插入图片描述

示例三:

  • 服务端代码
@PostMapping("/f23")
public String f23(Integer aa, Integer bb,@RequestBody String query) {
    return aa + ": " + bb + ": " + query;
}
  • 前端代码
<template>
  <div class="home">
    <button @click="postFun3">发送post请求</button>
  </div>
</template>
<script>
  import axios from 'axios'
  export default {
    name: 'Home',
    data () {
      return {
        queryInfo2: {
          username: 'zhangsan',
          password: '1234'
        }
      }
    },
    methods: {
      postFun3 () {
        let _this = this
        axios.post('http://localhost/blog/f23', _this.queryInfo2, {
          params: { //params表示url中传递的参数,它会拼接在url后面
            aa: 11,
            bb: 22
          }
        }).then(res => {
          console.log(res)
        })
      }
    }
  }
</script>

请求的url为:http://localhost/blog/f23?aa=11&bb=22 ,结果:
在这里插入图片描述
在这里插入图片描述

注意上面三个示例中传递到后台的username和password参数采用下面方式后台是无法获取到的:

@PostMapping("/f22")
public String f22(String username, String password) {
    return username + " : " + password;
}

原因是axios.post默认情况下传递到后台的数据是JSON格式的,通过设置POST请求头,可以告诉服务器请求主体的数据格式为kv的形式,比如:a=aaaa&b=bbbb。

示例:设置POST请求的格式

  • 后台代码
@PostMapping("/f21")
public String f21(@RequestBody String param) {
    return param;
}
  • 前端代码
<template>
  <div class="home">
    <button @click="postFun1">发送post请求</button>
    <button @click="postFun2">发送post请求</button>
  </div>
</template>
<script>
  import axios from 'axios'
  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
  import qs from 'qs'

  export default {
    name: 'Home',
    methods: {
      postFun1 () {
        let params = new URLSearchParams()
        params.append('username', 'zhangsan')
        params.append('password', '1234')
        axios.post('http://localhost/blog/f22', params).then(res => {
          console.log(res)
        })
      },
      postFun2 () {
        let params = qs.stringify({
          'username': 'zhangsan',
          'password': 1234
        })
        axios.post('http://localhost/blog/f22', params).then(res => {
          console.log(res)
        })
      },
    }
  }
</script>

前端会将参数以kv字符串的形式发送到后台:username=zhangsan&password=1234。上面示例前端网页中请求的也可以用下面控制器接收:

@PostMapping("/f22")
public String f22(String username, String password) {
    return username + " : " + password;
}

Put

示例一:

  • 前端
let _this = this
_this.$axios.put(`/user/${user.id}/status`).then(res => {  //注意,此处使用的是反斜杠
  console.log(res)
})
  • 后端
@PutMapping("/user/{userId}/status")
public Result changStatus(@PathVariable("userId") Integer userId){

}

示例二:

  • 前端
const param = {
  userId:1
}
_this.$axios.put('/user/update',param).then(res=>{
  console.log(res)
})
  • 后端
@PutMapping("/user/update")
public Result changStatus(@PathVariable("userId") Integer userId){

}

patch

前端

const param={
  ids:[1,3,5,8]
}
_this.$axios.patch('/user/p',param).then(res=>{
  console.log(res)
}),

Delete

前端

_this.$axios.delete('/user/delete',{
   params:{
     id:1
   }
 }).then(res=>{
   console.log(res)
 })

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/908025.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ARM--day7(cortex_M4核LED实验流程、异常源、异常处理模式、异常向量表、异常处理流程、软中断编程、cortex_A7核中断实验)

软中断代码&#xff1a;&#xff08;keil软件&#xff09; .text .global _start _start:1.构建异常向量表b resetb undef_interruptb software_interruptb prefetch_dataabortb data_abortb .b irqb fiq reset:2.系统一上电&#xff0c;程序运行在SVC模式1>>初始化SVC模…

pytorch lightning和pytorch版本对应

参见官方文档&#xff1a; https://lightning.ai/docs/pytorch/latest/versioning.html#compatibility-matrix 下图左一列&#xff08;lightning.pytorch&#xff09;安装命令&#xff1a;pip install lightning --use-feature2020-resolver 下图左一列&#xff08;pytorch_lig…

MySQL——基础——外连接

一、外连接查询语法&#xff1a;(实际开发中,左外连接的使用频率要高于右外连接) 左外连接 SELECT 字段列表 FROM 表1 LEFT [OUTER] JOIN 表2 ON 条件...; 相当于查询表1(左表)的所有数据 包含 表1和表2交集部分的数据 右外连接 SELECT 字段列表 FROM 表1 RIGHT [OUTER] JOIN …

在Qt窗口中添加右键菜单

在Qt窗口中添加右键菜单 基于鼠标的事件实现流程demo 基于窗口的菜单策略实现Qt::DefaultContextMenuQt::ActionsContextMenuQt::CustomContextMenu信号API 基于鼠标的事件实现 流程 需要使用:事件处理器函数(回调函数) 在当前窗口类中重写鼠标操作相关的的事件处理器函数&a…

Python支持下最新Noah-MP陆面模式站点、区域模拟及可视化分析技术教程

详情点击公众号链接&#xff1a;Python支持下最新Noah-MP陆面模式站点、区域模拟及可视化分析技术教程 Noah-MP 5.0模型&模型所需环境的搭建 陆面过程的主要研究内容&#xff08;陆表能量平衡、水循环、碳循环等&#xff09;&#xff0c;陆面过程研究的重要性。 图 1 陆面…

MyBatis-Plus快速开始[MyBatis-Plus系列] - 第482篇

悟纤&#xff1a;师傅&#xff0c;MyBatis-Plus被你介绍的这么神乎其乎&#xff0c;咱们还是来的点实际的吧。 师傅&#xff1a;那真是必须的&#xff0c;学习技术常用的一种方法&#xff0c;就是实践。 悟纤&#xff1a;贱贱更健康。 师傅&#xff1a;这… 师傅&#xff1a;…

”源启,征程“新员工入职考试题及答案

中电金信&#xff0c;新员工入职必修课《源启&#xff0c;征程》考试题及答案。 源启&#xff0c;征程 单选题&#xff0c;每题仅有一个正确的选项.&#xff08;本题型共有5题&#xff09; 1.“源启”诞生的背景是什么&#xff1f;&#xff08;10分&#xff09; A、国际关系…

macbook 加载模型报错:failed to load model

环境&#xff1a;macbook m1 conda python3.9 加载模型链接为&#xff1a;ggml-model-q4_0.bin 加载方式&#xff1a; from langchain.embeddings import LlamaCppEmbeddings embeddings LlamaCppEmbeddings(model_pathllama_path) 在linux上加载是正常的&#xff0c;但是…

互联网医院|线上医疗提升就医效率

互联网医院是一款在线医疗服务平台&#xff0c;旨在解决患者就医难、看病贵的问题。通过该应用&#xff0c;用户可以在线咨询医生、挂号就医、获取医疗信息和健康管理等服务&#xff0c;随着这几年人们对于线上医疗的认可&#xff0c;互联网医院系统功能也越来越完善&#xff0…

(二)Linux中安装docker(一篇就够)

一、安装docker &#xff08;1&#xff09;卸载系统之前的 docker 复制以下下命令执行&#xff1a; sudo yum remove docker \docker-client \docker-client-latest \docker-common \docker-latest \docker-latest-logrotate \docker-logrotate \docker-engine执行结果&…

使用vscode编写插件-php语言

https://blog.csdn.net/qq_45701130/article/details/125206645 一、环境搭建 1、安装 Visual Studio Code 2、安装 Node.js 3、安装 Git 4、安装生产插件代码的工具&#xff1a;npm install -g yo generator-code 二、创建工程 yo code 选择项解释&#xff1a; 选择编写扩…

Docker数据管理、网络通信和镜像创建

一、Docker 数据管理1、数据卷2、数据卷容器3、端口映射4、容器互联 二、Docker 镜像的创建1、基于现有的镜像创建1.1 首先启动一个镜像&#xff0c;在容器里做修改1.2 然后将修改后的容器提交为新的镜像&#xff0c;需要使用该容器的 ID 号创建新镜像 2、基于本地的模版创建3、…

RunnerGo中WebSocket、Dubbo、TCP/IP三种协议接口测试详解

大家好&#xff0c;RunnerGo作为一款一站式测试平台不断为用户提供更好的使用体验&#xff0c;最近得知RunnerGo新增对&#xff0c;WebSocket、Dubbo、TCP/IP&#xff0c;三种协议API的测试支持&#xff0c;本篇文章跟大家分享一下使用方法。 WebSocket协议 WebSocket 是一种…

【LeetCode】538.把二叉搜索树转换为累加树

题目 给出二叉 搜索 树的根节点&#xff0c;该树的节点值各不相同&#xff0c;请你将其转换为累加树&#xff08;Greater Sum Tree&#xff09;&#xff0c;使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。 提醒一下&#xff0c;二叉搜索树满足下列约束条件…

NAS个人云存储 - 手把手教你搭建Nextcloud个人云盘并实现公网远程访问

文章目录 摘要1. 环境搭建2. 测试局域网访问3. 内网穿透3.1 ubuntu本地安装cpolar3.2 创建隧道3.3 测试公网访问 4 配置固定http公网地址4.1 保留一个二级子域名4.1 配置固定二级子域名4.3 测试访问公网固定二级子域名 摘要 Nextcloud,它是ownCloud的一个分支,是一个文件共享服…

VSCode好用的插件

文章目录 前言1.Snippet Creator & easy snippet&#xff08;自定义代码&#xff09;2.Indent Rainbow&#xff08;代码缩进&#xff09;3.Chinese (Simplified) Language Pack&#xff08;中文包&#xff09;4.Path Intellisense&#xff08;路径提示&#xff09;5.Beauti…

GitKraken 详细图文教程

前言 写这篇文章的原因是组内的产品和美术同学&#xff0c;开始参与到git工作流中&#xff0c;但是网上又没有找到一个比较详细的使用教程&#xff0c;所以干脆就自己写了一个[doge]。文章的内容比较基础&#xff0c;介绍了Git内的一些基础概念和基本操作&#xff0c;适合零基…

游戏反外挂方案解析

近年来&#xff0c;游戏市场高速发展&#xff0c;随之而来的还有图谋利益的游戏黑产。在利益吸引下&#xff0c;游戏黑产扩张迅猛&#xff0c;已发展成具有庞大规模的产业链&#xff0c;市面上游戏受其侵扰的案例屡见不鲜。 据《FairGuard游戏安全2022年度报告》数据统计&…

明星翻包口播介绍产品视频的创意与实践

在当前社交媒体充斥着各种内容的时代&#xff0c;创意而有趣的内容形式成为品牌吸引受众目光的关键。明星翻包口播介绍产品视频&#xff0c;作为一种新颖的内容形式&#xff0c;不仅满足了观众对明星生活的好奇心&#xff0c;还将产品介绍融入其中&#xff0c;为品牌推广带来全…

Spring练习---28 (用户表和角色表分析,角色列表展示,角色层和Dao层的设置,页面展示操作)

84、下面进入我们的业务层面&#xff0c;进入我们的业务层面我们先分析一个东西&#xff0c;我们要分析用户和角色的关系&#xff0c;因为我们只有在分析完用户和角色之间的关系后&#xff0c;我们才知道表的关系&#xff0c;实体的关系 85、现在我们先画一张表&#xff0c;分析…