目录

一、axios模块

二、 axios使用方法

1.创建服务器端Express项目

2.创建服客户端Vite项目

3.在vite客户端安装axios

三、axios的六种请求

1.无参的get请求

2.带参的get请求

3. post请求

4.put请求

5.patch请求

6.delete请求

四、 axios的数据封装格式

五、vue-axios模块

1.安装

2.在main.js文件中进行全局的配置


一、axios模块

axios是一个基于promise的http客户端请求工具,可以用在浏览器和node.js中。

可以提供以下服务:

  1. 从浏览器中创建XMLHttpRequest2:异步请求对象
  2. 从node.js 创建http请求
  3. 支持PromiseAPl:请求的返回值是Promise对象(resolve、reject)
  4. 拦截请求和响应
  5. 转换请求数据和响应数据
  6. 取消请求
  7. 自动转换JSON数据
  8. 客户端支持防御XSRF

二、 axios使用方法

1.创建服务器端Express项目

(1)在webstorm创建express项目

(2)点击右上角运行按钮后,项目运行在3000端口号上

(3)在webtorm中安装跨域模块

npm install cors

在express服务器端进行此模块的安装,因为在前后端交互时,浏览器出于安全考虑,会将js代码跨域模块的访问进行拦截,所以为了进行跨域访问,需要安装这个cors模块。

(4)在app.js中导入跨域模块进行使用

(5)在uers.js路由文件中创建测试路由

(6)重新运行后,在接口测试软件中测试结果

2.创建服客户端Vite项目

(1)在webstorm创建vite项目

(2)点击右下角Run 'npm install',安装依赖

(3)如下图所示进行运行配置

(4)点击右上角运行按钮,运行项目

注意:如果出现服务器端于客户端端口相同的情况,会默认打开服务器端,此时需要将服务器端中“bin文件→www”中的端口改成与客户端不同的端口。

3.在vite客户端安装axios

(1)安装axios

npm install axios

(2)新建模块

三、axios的六种请求

1.无参的get请求

方式一:

axios({ methods: 'get' , url: '/url' ).then (res =>{console.log (res)}).catch(err =>{console.error(err);
}

方式二:

axios.get('/url').then((result)=>{console.log(result)}).catch((err)=>{console.log(err)
})

客户端Test.vue代码段:(第二种方式)

<template><!-- 给按钮绑定名为myClick的click事件 --><button @click="myClick">Get请求</button><br/><br/><!-- 若要页面显示,需加1--><p>{{ responseText }}</p>
</template><script>
// 导入axios
import axios from 'axios';
export default {name: "Test",// 若要页面显示,需要加2data(){return{responseText:''}},methods:{myClick(){axios.get('http://localhost:3000/users/test').then((result)=>{// 若要页面显示,需要加3this.responseText =result.data.msg// 打印在终端console.log(result.data.msg)}).catch((err)=>{console.log(err)})}}
}
</script><style scoped></style>

客户端App.vue代码段:

<script setup>
import Test from "./components/Test.vue";
</script><template><img src="./assets/vue.svg" class="logo vue" alt="Vue logo" /><br/><Test/>
</template>

服务器端:
user.js代码段:

// 测试路由:http://localhost:3000/users/test
router.get('/test',(req, res) => {res.json({code:1001,msg:测试信息})
})

效果图:

​​​​​​​

如何把数组响应给客户端?

客户端Test.vue代码段

<template><!-- 给按钮绑定名为myClick的click事件 --><button @click="myClick">Get请求</button>
</template><script>
// 导入axios
import axios from 'axios';
export default {name: "Test",// 若要页面显示,需要加2data() {return {//如何把数组相应给客户端arr:[]}},methods: {myClick() {axios({url: 'http://localhost:3000/users/test',methods: 'get',}).then((result) => {this.arr = result.data.msg;//打印数组中全部内容console.log(this.arr)//打印一组内容//console.log(this.arr[0])}).catch((err) => {console.log(err)})}}
}</script><style scoped></style>

客户端App.vue代码段:

<script setup>
import Test from "./components/Test.vue";
</script><template><img src="./assets/vue.svg" class="logo vue" alt="Vue logo" /><br/><Test/>
</template>

服务器端:
user.js代码段:

var express = require('express');
var router = express.Router();/* GET users listing. */
router.get('/', function(req, res, next) {res.send('respond with a resource');
});//非敏感性数据用get请求,敏感性(传参)用post请求
/* 测试路由:http://localhost:3000/users/test */
router.get('/test',(req, res) => {let objArr = [{id:1001,name: '刘备',gender: '男',age: 36},{id:1002,name: '关羽',gender: '男',age: 32},{id:1003,name: '张飞',gender: '男',age: 28}]res.json({code: 1001,msg: objArr})
})module.exports = router;

效果图:

2.带参的get请求

方式一:

 axios.get('/url',{params: {id: 12}}).then((result)=>{}).catch((err)=>{})

方式二:

 axios({url:'url',methods: 'get',params: {参数名: 参数值}}).then((result)=>{请求成功的处理代码}).catch((err)=>{失败的处理代码})

客户端Test.vue代码段:(两种方式写法如下)

<template><!-- 给按钮绑定名为myClick的click事件 --><button @click="myClick">Get请求</button><br/><br/><p>{{ responseText }}</p>
</template><script>
// 导入axios
import axios from 'axios';
export default {name: "Test",data(){return {responseText: ''}},methods: {// 方式一:myClick() {axios.get('http://localhost:3000/users/test', {params: {userName: '张三'}}).then((result) => {this.responseText = result.data.msgconsole.log(result.data.msg)}).catch((err) => {console.log(err)})// 方式二:// myClick() {// axios({//   url: 'http://localhost:3000/users/test',//   methods: 'get',//   params:{//     userName:'刘备'//   }// }).then((result) => {//   this.responseText = result.data.msg;//   // console.log(result.data.msg)// }).catch((err) => {//   console.log(err)// })}}
}</script><style scoped></style>

 客户端App.vue代码段:

<script setup>
import Test from "./components/Test.vue";
</script><template><img src="./assets/vue.svg" class="logo vue" alt="Vue logo" /><br/><Test/>
</template>

服务器端user.js代码段:

服务器端使用‘req.query.参数名’ (格式接收)

// 测试路由:http://localhost:3000/users/test
router.get('/test',(req, res) => {let name = req.query.userNameres.json({code:1001,msg:name})
})

效果图:

3. post请求

方式一:

    axios.post('url',{参数名:参数值}).then((result)=>{}).catch((err)=>{})

方式二:

   axios({url:'url',methods: 'post',data: {参数名:参数值}}).then((result)=>{}).catch((err)=>{})

 

客户端Test.vue代码段:(两种方式写法如下)

<template><button @click="myClick">Get请求</button><br/><br/><button @click="postClick">Post请求</button><p>{{ responseText }}</p><p>{{ postText }}</p>
</template><script>
import axios from 'axios';
export default {name: "Test",data(){return{responseText:'',postText:''}},methods:{postClick(){// 方式一:// axios({//   url:'http://localhost:3000/users/post',//   methods:'post',//   data:{//     postId:'S_POST'//   }// }).then((result)=>{//   this.postText=result.data.info;// }).catch((err)=>{//   console.log(err)// })// 方式二:axios.post('http://localhost:3000/users/post',{postId:'S_POST'}).then((result)=>{this.postText=result.data.info;}).then((result)=>{this.postText=result.data.info;}).catch((err)=>{console.log(err)})}
}
</script><style scoped></style>

服务器端user.js代码段:

服务器端使用‘req.body.参数名’ 获取数据

//测试路由:http://localhost:3000/users/post
router.post('/post',(req, res) => {let id=req.body.postId;res.json({code:1001,info:id})
})

效果图:

4.put请求

put请求用于对数据全部进行更新时使用。请求时传参的方式、服务器端获取数据的方式与post请求类似。

注意:登录验证时建议用post请求,更新数据时建议用put请求。

5.patch请求

patch请求只对更改过的数据进行更新。该请求与post请求类似,只是请求方法不同。

6.delete请求

delete请求用于删除数据。可以采用类似get方式或post方式的写法。

方式一:

类似于get方式:服务器端以’req.query.参数名’的格式获取请求数据

   axios.deleter('url',{params:{参数名:参数值}}).then((res)=>{}).catch((err)=>{})

方式二:

类似于post方式:服务器端以’req.body.参数名’的格式获取请求数据

    axios.deleter('url',{data:{参数名:参数值}}).then((res)=>{}).catch((err)=>{})

四、 axios的数据封装格式

1.data:服务器端响应的数据

data: { },

2.status:请求的状态码

status:200,

3.statusText:状态码对应的状态信息

statusText:"OK",

4.headers:服务器端响应头信息

headers:{ },

5.config:请求的配置信息

config: { },

五、vue-axios模块

 vue-axios模块是针对Vue对axios进行了一层简单的包装。

1.安装

npm install vue-axios     (前提:已经安装过axios ——见上文)

2.在main.js文件中进行全局的配置

  • 导入axios和vue-axios
//导入axios和vue-axios
import axios from 'axios';
import VueAxios from "vue-axios";
  • 注册
//定义挂载根组件
const app = createApp(App)//在根组件中注册axios
app.use(VueAxios,axios)//根组件挂载
app.mount('#app')

main.js文件:

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
//导入axios和vue-axios
import axios from 'axios';
import VueAxios from "vue-axios";//定义挂载根组件
const app = createApp(App)//在根组件中注册axios
app.use(VueAxios,axios)//根组件挂载
app.mount('#app')

安装此模块后,不需要在每个组件中单独导入axios,只需将axios改为this.axios,如下:

【vue】axios和vue-axios请求模块相关推荐

  1. Vue使用axios,设置axios请求格式为form-data

    Vue使用axios,设置axios请求格式为form-data 这个老生常谈了,还是先记录一遍,方面后面自己查. !!! 设置form-data请求格式直接翻到后面看. 1. 安装axios 在项目 ...

  2. Axios的Vue插件(添加全局请求/响应拦截器)

    /**  * @file Axios的Vue插件(添加全局请求/响应拦截器)  */ // https://github.com/mzabriskie/axios import axios from ...

  3. vue 使用axios 出现跨域请求的两种解决方法

    vue 使用axios 出现跨域请求的两种解决方法 参考文章: (1)vue 使用axios 出现跨域请求的两种解决方法 (2)https://www.cnblogs.com/wangshengli5 ...

  4. Vue安装并使用axios发送请求

    前言 本文主要介绍的是使用在Vue项目中安装并使用axios发送请求 axios介绍 axios是一种Web数据交互方式 它是一个基于promise的网络请求库,作用于node.js和浏览器中,它是 ...

  5. Vue乱搞系列之axios发起表单请求

    原文地址:https://www.jianshu.com/p/b22d03dfe006 简单介绍 在半年前尤大就不推荐使用vue-resource了,好像我这么没安全感的人,没人维护的东西不敢碰. 1 ...

  6. 在vue项目中对axios进行封装

    在vue项目中对axios进行封装 1.引入axios,qs模块 import axios from 'axios'; import Qs from "qs"; import st ...

  7. Vue学习笔记(二)—— vue项目中使用axios

    一.文档链接 axios文档 vue开发插件 二.axios 简介 axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征: 从浏览器中创建 XML ...

  8. vue项目中对axios的全局封装

    项目中接口会很多,个人喜欢创建api文件对请求统一管理 1.新建api文件夹,文件夹下创建 axios.js,login.js 2.  axios.js import axios from 'axio ...

  9. vue-router路由、mixin混入、vue-resource、axios、计算属性watch、moment.js、vuex、vue-cli、数据双向绑定、搭建vue环境、vue实例、配置启动项

    路由vue-router介绍: // 1.前端路由核心:锚点值的改变,根据不同的锚点值,渲染指定dom位置的不同数据.// 2.vue中,模板数据不是通过ajax请求的,而是调用函数获取到模板内容// ...

最新文章

  1. (C++)strlen(),strcmp(),strcpy(),strcat()用法
  2. QT-Creator+SDK+编译器+自定义配置
  3. vue-cookies使用方法,vue中使用获取cookie
  4. kitti pkl可视化_KITTI 3D Lidar 数据可视化
  5. Hotel POJ - 3667(线段树 + 区间合并
  6. 美国留学计算机网络技术,美国留学计算机专业详解
  7. 统计学习方法 李航 读书笔记
  8. 19岁黑客找到暴露 Facebook 页面管理员的缺陷,获4500美元奖励
  9. BZOJ1768 : [Ceoi2009]logs
  10. 【案例】MySQL count操作优化案例一则
  11. Qt获取时间秒数,毫秒数,当前时间
  12. couchbase java 手册_Couchbase之环境搭建与基于Java的测试
  13. 讲解HTML和CSS(超详细)
  14. 【判断一个文件是否为 excel 文件的正则表达式】
  15. Linux添加开机自启服务
  16. win10桌面版outlook邮箱配置流程
  17. 微信小程序web-view使用audio标签播放音频文件时无法自动播放的问题
  18. 河北省保定市谷歌卫星地图下载
  19. OPC UA协议网关
  20. lib linux.so2 bad,linux – docker,openmpi和/ proc / mounts行的意外...

热门文章

  1. PyQt之QComboBox(下拉列表框)动态添加
  2. 解决应用和功能列表中存在已卸载的程序
  3. SimpleFOC(七)——STM32(Bluepill)的应用
  4. Android各版本名称
  5. 打印机故障---看起来没有什么问题,就是无法打印
  6. 【论文解读】地空双模式车辆的自主自适应导航
  7. wps怎样批量删掉批注
  8. EXCEL VBA复制含公式数据源替换为数值
  9. 在ROS中使用C++中,ros/ros.h报错/找不到
  10. 一个2-3年的运营,应该有的6点觉悟