Axios介绍与应用
目录
1.技术概述
简单介绍
Axios是一个基于Promise的现代化HTTP客户端库,既可以在浏览器端使用,也可以在Node.js环境中使用。它支持所有主流的浏览器,包括IE8+,并提供了许多易用的特性和配置选项,使得发送HTTP请求和处理响应变得更加简单和可控。Axios还支持取消请求、拦截请求和响应、转换请求和响应数据等高级功能,是目前最为流行和实用的HTTP客户端之一。
Axios特性
- 从浏览器创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 自动转换JSON数据
运用情况
当我们需要使用前后端时候,前端需要向后端请求数据的同时,往往我们都通过Axios进行网络请求,而若是项目中使用Jquery时候,则不需要用到Axios,Jquery即可发送请求。
2.技术详述
在初期刚刚开始使用axios的时候,我使用axios主要是直接嵌在JS当中,这样子的话,方便进行查看,以及及时地发现问题。
axios.post("/api/v1/chat/new", {
apiKey: apikey.value,
modelId: model.value,
content: {
personalityId: characterid.value, //构造system
user: textarea.value, // user input
},
}) //进行post请求,然后进行处理
.then(async (response) => {
let firstchat: firstchat = response.data;
messages.value[indexnumber.value].chatId=firstchat.chatId;
changeTitle.value.index = indexnumber.value;
changeTitle.value.id = firstchat.chatId;
changeTitle.value.title = firstchat.content.title;
try { //打开数据库,将内容填充进去
await db.open();
db.messagetitles.add({
chatId: firstchat.chatId,
title: firstchat.content.title,
});
db.messages.add({
chatId: firstchat.chatId,
userContent: firstchat.content.user,
assistantContent: firstchat.content.assistant,
});
} finally {
db.close();
}
messages.value[indexnumber.value].chatId = firstchat.chatId;
messages.value[indexnumber.value].messages.push({
type: "assistant",
content: firstchat.content.assistant,
});
});
而后面在后期进行写Axios的时候,我们便将Axios进行整合,方便后期进行URL的修改,我们便会将Axios进行提出,这样子若是后期需要修改的时候,则只需要在同一地块进行修改,方便快捷。
import type { getFirstMessage, getMessage } from "./res"
import type { sendMessage, firstSendMessage, deleteChat } from "./req"
import axios from "axios";
const URL = {
FIRSTCHAT: "/api/v1/chat/new",
CHAT: "/api/v1/chat/chat",
DELETE: "/api/v1/chat/deletechat"
}
export async function getFirst(req: firstSendMessage): Promise<getFirstMessage> {
try {
const response = await axios.post(URL.FIRSTCHAT, req)
const resData: getFirstMessage = response.data;
return resData;
} catch (error) {
console.log("network error")
return {
chatId: req.chatId,
modelId: req.modelId,
content: {
personalityId: req.content.personalityId,
user: req.content.user, // user input
assistant: '网络或者输入错误,请重新输入',
title: '你好' + req.chatId,
},
}
}
}
export async function getmessage(req: sendMessage): Promise<getMessage> {
try {
const response = await axios.post(URL.CHAT, req)
const resData: getMessage = response.data;
return resData;
} catch (error) {
return {
chatId: req.chatId,
content: {
user: req.content.user,
assistant: '网络或者输入错误,请重新输入',
}
}
}
}
export async function deletemessage(req: deleteChat) {
try {
await axios.post(URL.DELETE, req)
} catch (error) {
console.error(error);
throw new Error('Failed to delete message');
}
}
3.开发中遇到的问题
- 开始阶段
在开始阶段的时候,由于对Axios并不是非常的了解,导致了并不太会使用,会导致一些关于Axios的请求体并不会符合标准的格式,以及响应体的数据没有正确体现,比如无法正常返回Axios的状态或者。 - 格式问题
其次遇到的最难受的就是前后端对接产生的问题。后端发布的API文档,自己却没有按照文档来进行数据的传输,比如后端文档中要求返回的格式是string类型,但是其实际传过来的类型,这样子看起来传过来的数据并没有什么问题,由于JS的弱类型,也能够接收,但是当我们实际要进行数据使用的时候,却出现了大问题,这个数据并不存在,太过痛苦了!!!!!!!!!!!! - 同异步问题
在开始的时候,我们并没有整合Axios,而是直接放在JS中进行处理,但是在我们整理后,我们往往在网页中时候的时候都会添加一句await
export async function getFirst(req: firstSendMessage): Promise<getFirstMessage> {
try {
const response = await axios.post(URL.FIRSTCHAT, req)
const resData: getFirstMessage = response.data;
return resData;
} catch (error) {
console.log("network error")
return {
chatId: req.chatId,
modelId: req.modelId,
content: {
personalityId: req.content.personalityId,
user: req.content.user, // user input
assistant: '网络或者输入错误,请重新输入',
title: '你好' + req.chatId,
},
}
}
}
//在其他网页中进行函数的调用
const firstchat: getFirstMessage = await getFirst(firstsendmessage);
这会出现一个同异步的现象,便是数据并不会等待firstchat中的数据出来之后再渲染,而是会继续执行,并不会等待getFirst函数进行响应,这会出现数据在网页上并没有成功渲染出来的问题。而为了解决这一个问题时,我们就需要将异步操作改成同步操作,这样子才能够正确的渲染数据。
//这是选择选项后,把选择的选项传达给后端,后端返回新的选项的api
export async function sendchoice(req: sendChoice):Promise<getNewChoiceAndStory> {
try{
const response = await axios.post(URL.SendChoice,req);
const resData: getNewChoiceAndStory = response.data;
return resData;
}catch (error) {
// 处理错误
return {
story: "游戏结束了或因为网络问题而终止",//故事的发展剧情
choice: [],
round: -1,
};
}
}
//这是具体调用的函数
function selectOption(next: number, choice: string, content: string) {
//应先让它,点击之后进入加载
isloading.value = true;
try {
const sendachoice: sendChoice = {
apiKey: apiKey.value,
choiceID: choice, //A,B,C,D
modelId: ModelId.value,
};
sendchoice(sendachoice)
.then((responseData) => {
const getnewchoice: getNewChoiceAndStory = responseData;
stories.value.push(getnewchoice);
})
.finally(() => {
isloading.value = false;//放在finally中保证了在获得数据后,
//加载才会结束,否则如果直接放在外面,像后端还没有请求出结果,
/便会直接渲染,导致数据没有出现的问题
});
} catch {
ElMessage.info("请求出现故障,请稍等");
}
}
4.总结
在本次的团队项目当中,由于是第一次进行Axios的编写,起初是不太适应的,但是随着慢慢学习,Axios也越发的容易上手,并且可以进行操作。对于开发者来说,Axios是一个非常实用、灵活且易用的HTTP客户端库,可以帮助开发者更加方便地发送HTTP请求并处理响应数据。