javaWeb axios

Axios

一、简介

Axios 是一个基于 promise 的网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。

特性:

从浏览器创建 XMLHttpRequests

从 node.js 创建 http 请求

支持 Promise API

拦截请求和响应

转换请求和响应数据

取消请求

自动转换JSON数据

客户端支持防御XSRF

二、具体实例介绍

App.Vue

```html

<script setup type="module">

import axios from 'axios'

import { onMounted,reactive } from 'vue';

let jsonData =reactive({code:1,content:'我努力不是为了你而是因为你'})

let getLoveMessage =()=>{

axios({//axios方法返回一个promise的实例

method:"post", // 请求方式

url:"https://api.uomg.com/api/rand.qinghua?format=json", // 请求的url

data:{ // 当请求方式为post时,data下的数据以JSON串放入请求体,否则以key=value形式放url后

username:"123456"

}

}).then( function (response){//响应成功时要执行的函数

console.log(response)

Object.assign(jsonData,response.data)

}).catch(function (error){// 响应失败时要执行的函数

console.log(error)

})

}

/* 通过onMounted生命周期,自动加载一次 */

onMounted(()=>{

getLoveMessage()

})

</script>

<template>

<div>

<h1>今日土味情话:{{jsonData.content}}</h1>

<button @click="getLoveMessage">获取今日土味情话</button>

</div>

</template>

<style scoped>

</style>

Axios get和post方法

> 配置添加语法

``` javascript

axios.get(url[, config])

axios.get(url,{

上面指定配置key:配置值,

上面指定配置key:配置值

})

axios.post(url[, data[, config]])

axios.post(url,{key:value //此位置数据,没有空对象即可{}},{

上面指定配置key:配置值,

上面指定配置key:配置值

})

```

> 测试get参数

async function getMessage(){

return await axios.get(

Url,

{向url后添加的键值对参数},

Headers:{设置请求头}

)

}

``` html

<script setup type="module">

import axios from 'axios'

import { onMounted,ref,reactive,toRaw } from 'vue';

let jsonData =reactive({code:1,content:'我努力不是为了你而是因为你'})

let getLoveWords= async ()=>{

try{

return await axios.get(

'https://api.uomg.com/api/rand.qinghua',

{

params:{// 向url后添加的键值对参数

format:'json',

username:'zhangsan',

password:'123456'

},

headers:{// 设置请求头

'Accept' : 'application/json, text/plain, text/html,*/*'

}

}

)

}catch (e){

return await e

}

}

let getLoveMessage =()=>{

let {data} = await getLoveWords()

Object.assign(message,data)

}

/* 通过onMounted生命周期,自动加载一次 */

onMounted(()=>{

getLoveMessage()

})

</script>

<template>

<div>

<h1>今日土味情话:{{jsonData.content}}</h1>

<button @click="getLoveMessage">获取今日土味情话</button>

</div>

</template>

<style scoped>

</style>

```

> 测试post参数

async function PostMessage(){

return await axios.post(

{url的地址},

{请求体中的json数据},

{需要放进标头的键值对参数}

)

}

```html

<script setup type="module">

import axios from 'axios'

import { onMounted,ref,reactive,toRaw } from 'vue';

let jsonData =reactive({code:1,content:'我努力不是为了你而是因为你'})

let getLoveWords= async ()=>{

try{

return await axios.post(

'https://api.uomg.com/api/rand.qinghua',

{//请求体中的JSON数据

username:'zhangsan',

password:'123456'

},

{// 键值对参数

params:{// url上拼接的键值对参数

format:'json',

},

headers:{// 请求头

'Accept' : 'application/json, text/plain, text/html,*/*',

'X-Requested-With': 'XMLHttpRequest'

}

}

)

}catch (e){

return await e

}

}

let getLoveMessage =()=>{

let {data} = await getLoveWords()

Object.assign(message,data)

}

/* 通过onMounted生命周期,自动加载一次 */

onMounted(()=>{

getLoveMessage()

})

</script>

<template>

<div>

<h1>今日土味情话:{{jsonData.content}}</h1>

<button @click="getLoveMessage">获取今日土味情话</button>

</div>

</template>

<style scoped>

</style>

```

拦截器

如果想在axios发送请求之前,或者是数据响应回来在执行then方法之前做一些额外的工作,可以通过拦截器完成

添加请求拦截器 请求发送之前:

axios.interceptors.request.use(

function (config) {

// 在发送请求之前做些什么

return config;//必须返回config

},

function (error) {

// 对请求错误做些什么

return Promise.reject(error);

}

);

添加响应拦截器 数据响应回来 :

axios.interceptors.response.use(

function (response) {

// 2xx 范围内的状态码都会触发该函数。

// 对响应数据做点什么

return response;

},

function (error) {

// 超出 2xx 范围的状态码都会触发该函数。

// 对响应错误做点什么

return Promise.reject(error);

}

);

  • 定义src/axios.js提取拦截器和配置语法

Axios.js:

import axios from 'axios'

// 创建instance实例

const instance = axios.create({

baseURL:'https://api.uomg.com',

timeout:10000

})

// 添加请求拦截

instance.interceptors.request.use(

// 设置请求头配置信息

config=>{

//处理指定的请求头

console.log("before request")

config.headers.Accept = 'application/json, text/plain, text/html,*/*'

return config

},

// 设置请求错误处理函数

error=>{

console.log("request error")

return Promise.reject(error)

}

)

// 添加响应拦截器

instance.interceptors.response.use(

// 设置响应正确时的处理函数

response=>{

console.log("after success response")

console.log(response)

return response

},

// 设置响应异常时的处理函数

error=>{

console.log("after fail response")

console.log(error)

return Promise.reject(error)

}

)

// 默认导出

export default instance

```

  • App.vue

```html

<script setup type="module">

// 导入我们自己定义的axios.js文件,而不是导入axios依赖

import axios from './axios.js'

import { onMounted,ref,reactive,toRaw } from 'vue';

let jsonData =reactive({code:1,content:'我努力不是为了你而是因为你'})

let getLoveWords= async ()=>{

try{

return await axios.post(

'api/rand.qinghua',

{

username:'zhangsan',

password:'123456'

},//请求体中的JSON数据

{

params:{

format:'json',

}

}// 其他键值对参数

)

}catch (e){

return await e

}

}

let getLoveMessage =()=>{

// 这里返回的是一个fullfilled状态的promise

getLoveWords().then(

(response) =>{

console.log("after getloveWords")

console.log(response)

Object.assign(jsonData,response.data)

}

)

}

/* 通过onMounted生命周期,自动加载一次 */

onMounted(()=>{

getLoveMessage()

})

</script>

<template>

<div>

<h1>今日土味情话:{{jsonData.content}}</h1>

<button @click="getLoveMessage">获取今日土味情话</button>

</div>

</template>

<style scoped>

</style>

相关推荐
全栈独立开发者2 分钟前
软考架构师实战:Spring Boot 3.5 + DeepSeek 开发 AI 应用,上线 24 小时数据复盘(2C1G 服务器抗压实录)
java·spring boot·后端
CoderYanger4 分钟前
D.二分查找-基础-2529. 正整数和负整数的最大计数
java·开发语言·数据结构·算法·leetcode·职场和发展
小光学长5 分钟前
ssm农民养殖经验交流与分享平台bc046578(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·数据库·spring
E***U9456 分钟前
Java 校招 / 社招:Spring Boot 项目实战指南
java·开发语言·spring boot
在坚持一下我可没意见7 分钟前
Spring 开发小白学习过程中常用通用配置文件,即拿即用!(持续更新中)
java·数据库·后端·学习·spring·tomcat·mybatis
柯南二号11 分钟前
【后端】【Java】《Spring Boot 统一接口耗时统计实践:基于 HandlerInterceptor 的工程级方案》
java·开发语言·数据库
m0_7400437312 分钟前
SpringBoot03-Mybatis框架入门
java·数据库·spring boot·sql·spring·mybatis
默 语14 分钟前
用Java撸一个AI聊天机器人:从零到一的踩坑实录
java·人工智能·spring·ai·机器人·spring ai
脸大是真的好~15 分钟前
黑马消息队列-rabbitMQ2-生产者重连机制-生产者确认机制-数据持久化-LazyQueue-消费者确认机制-失败重试机制-重试耗尽告警手动处理-
java·缓存·中间件
一 乐17 分钟前
心理健康管理|基于springboot + vue心理健康管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端