一文詳解fetch,ajax,axios的區(qū)別以及使用
fetch,ajax,axios這些都是發(fā)起前端請(qǐng)求的工具,除了這些外還有jquery的$.ajax。ajax和$.ajax都是基于XMLHttpRequest。
介紹下XMLHttpRequest
XMLHttpRequest是一種在瀏覽器中用于與服務(wù)器進(jìn)行異步通信的對(duì)象,它是實(shí)現(xiàn) AJAX(Asynchronous JavaScript and XML,異步的 JavaScript 與 XML 技術(shù))的核心。通過 XMLHttpRequest,可以在不刷新整個(gè)頁面的情況下與服務(wù)器交換數(shù)據(jù)并更新部分網(wǎng)頁內(nèi)容。而jquery的$.ajax簡(jiǎn)化了XMLHttpRequest的使用。
區(qū)別
ajax:是最早用于實(shí)現(xiàn)異步數(shù)據(jù)交互的技術(shù),出現(xiàn)時(shí)間較早。兼容性非常好,能在所有主流瀏覽器(包括一些較舊版本的瀏覽器)中使用。
fetch:是 ES6 引入的新的 API,現(xiàn)代瀏覽器基本都支持,但在一些舊版本瀏覽器中需要使用 polyfill 來實(shí)現(xiàn)兼容。
axios:是一個(gè)基于promise的 HTTP 客戶端,用于瀏覽器和 Node.js。由于是第三方庫,使用時(shí)需要引入,不過它通過內(nèi)部處理兼容了不同瀏覽器,也能在 Node.js 環(huán)境使用。
使用
這里使用express框架創(chuàng)建一個(gè)簡(jiǎn)單的node服務(wù),里面有一個(gè)接口,以便演示使用。
node后端
創(chuàng)建好項(xiàng)目文件夾后在cmd里面輸入命令
npm i express
使用cors中間件來配置跨域,安裝命令
npm install cors
app.js
// 引入 express 模塊
const express = require('express');
// 引入 cors 模塊
const cors = require('cors');
// 創(chuàng)建 express 應(yīng)用實(shí)例
const app = express();
// 定義端口號(hào)
const port = 3000;
// 配置 cors 中間件,允許來自 8080 端口的跨域請(qǐng)求
const corsOptions = {
origin: 'http://localhost:8080',
};
app.use(cors(corsOptions));
// 定義一個(gè) GET 請(qǐng)求的接口
app.get('/api/data', (req, res) => {
// 定義要返回的數(shù)據(jù)
const data = {
message: '接口的數(shù)據(jù)',
list: [1, 2, 3]
};
// 設(shè)置響應(yīng)頭,指定返回的數(shù)據(jù)格式為 JSON
res.setHeader('Content-Type', 'application/json');
// 發(fā)送 JSON 數(shù)據(jù)作為響應(yīng)
res.send(JSON.stringify(data));
});
// 啟動(dòng)服務(wù)器,監(jiān)聽指定端口
app.listen(port, () => {
console.log(`服務(wù)器正在運(yùn)行,訪問地址為 http://localhost:${port}/api/data`);
});打開終端輸入node app.js 啟動(dòng),看到這個(gè)表示成功了,點(diǎn)擊地址可以看到接口返回的數(shù)據(jù)


fetch
<template>
<div id="box">
<button @click="getDate">fetch</button>
</div>
</template>
<script>
export default {
name: "App",
methods: {
async getDate() {
const res = await fetch("http://localhost:3000/api/data");
console.log("res", res);
// 使用 res.json() 方法將響應(yīng)體解析為 JSON 格式
const data = await res.json();
console.log("data", data);
},
},
};
</script>運(yùn)行結(jié)果,打印可以看到已經(jīng)拿到了接口的數(shù)據(jù)了,在瀏覽器網(wǎng)絡(luò)中也可以看到請(qǐng)求已經(jīng)成功了


ajax
<template>
<div id="box">
<button @click="getData2">ajax</button>
</div>
</template>
<script>
export default {
name: "App",
methods: {
getData2() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:3000/api/data", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const res2 = JSON.parse(xhr.responseText);
console.log("res2", res2);
} else {
console.error("AJAX 請(qǐng)求出錯(cuò),狀態(tài)碼:", xhr.status);
}
}
};
xhr.send();
},
},
};
</script>打印結(jié)果

axios
axios是第三方庫,在使用前需要安裝,命令
npm install axios
<template>
<div id="box">
<button @click="getData3">axios</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: "App",
methods: {
async getData3(){
const res3=await axios.get('http://localhost:3000/api/data');
console.log('res3',res3);
}
},
};
</script>打印結(jié)果

axios在實(shí)際開發(fā)中用的比較多,這里在演示下axios發(fā)put,post,delete請(qǐng)求。首先修改下后端代碼,添加上put,post,delete接口。(修改完代碼后記得重啟下--在執(zhí)行一次node app.js)
// 引入 express 模塊
const express = require('express');
// 引入 cors 模塊
const cors = require('cors');
// 創(chuàng)建 express 應(yīng)用實(shí)例
const app = express();
// 定義端口號(hào)
const port = 3000;
// 配置 cors 中間件,允許來自 8080 端口的跨域請(qǐng)求
const corsOptions = {
origin: 'http://localhost:8080',
};
app.use(cors(corsOptions));
// 解析請(qǐng)求體中的 JSON 數(shù)據(jù)
app.use(express.json());
// 聲明一個(gè)數(shù)據(jù)對(duì)象
let data = {
message: '接口的數(shù)據(jù)',
list: [1, 2, 3]
};
// 定義一個(gè) GET 請(qǐng)求的接口,用于獲取數(shù)據(jù)
app.get('/api/data', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(data));
});
// 定義一個(gè) POST 請(qǐng)求的接口,用于新增數(shù)據(jù)
app.post('/api/data', (req, res) => {
const newData = req.body;
// 假設(shè)新增的數(shù)據(jù)是添加到 list 數(shù)組中
if (newData.value) {
data.list.push(newData.value);
}
const responseData = {
message: 'POST 請(qǐng)求處理成功,數(shù)據(jù)已新增',
currentData: data
};
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(responseData));
});
// 定義一個(gè) PUT 請(qǐng)求的接口,用于更新數(shù)據(jù)
app.put('/api/data', (req, res) => {
const updatedData = req.body;
// 假設(shè)更新的數(shù)據(jù)是替換 list 數(shù)組
if (updatedData.list) {
data.list = updatedData.list;
}
const responseData = {
message: 'PUT 請(qǐng)求處理成功,數(shù)據(jù)已更新',
currentData: data
};
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(responseData));
});
// 定義一個(gè) DELETE 請(qǐng)求的接口,用于刪除數(shù)據(jù)
app.delete('/api/data', (req, res) => {
const deleteIndex = req.body.index;
if (deleteIndex!== undefined && deleteIndex >= 0 && deleteIndex < data.list.length) {
data.list.splice(deleteIndex, 1);
}
const responseData = {
message: 'DELETE 請(qǐng)求處理成功,數(shù)據(jù)已刪除',
currentData: data
};
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(responseData));
});
// 啟動(dòng)服務(wù)器,監(jiān)聽指定端口
app.listen(port, () => {
console.log(`服務(wù)器正在運(yùn)行,訪問地址為 http://localhost:${port}/api/data`);
});前端代碼
<template>
<div id="box">
<button @click="getData">獲取數(shù)據(jù)</button>
<button @click="addData">新增數(shù)據(jù)</button>
<button @click="updateData">更新數(shù)據(jù)</button>
<button @click="deleteData">刪除數(shù)據(jù)</button>
info:{{ info.message }} {{ info.list }}
</div>
</template>
<script>
import axios from 'axios';
export default {
name: "App",
data(){
return {
info:{},
}
},
methods: {
// 獲取數(shù)據(jù)
async getData() {
try {
const response = await axios.get('http://localhost:3000/api/data');
this.info = response.data;
} catch (error) {
console.error('獲取數(shù)據(jù)失敗:', error);
}
},
// 新增數(shù)據(jù)
async addData() {
try {
const newData = { value: 4 };
await axios.post('http://localhost:3000/api/data', newData);
//調(diào)用獲取數(shù)據(jù)接口來獲取最新的數(shù)據(jù),await 確保接口完成后在打印
//不加await可能會(huì)打印新增之前的舊值
await this.getData();
console.info('新增后',this.info );
} catch (error) {
console.error('新增數(shù)據(jù)失敗:', error);
}
},
// 更新數(shù)據(jù)
async updateData() {
try {
const updatedData = { list: [5, 6, 7] };
await axios.put('http://localhost:3000/api/data', updatedData);
await this.getData();
console.info('更新后',this.info );
} catch (error) {
console.error('更新數(shù)據(jù)失敗:', error);
}
},
// 刪除數(shù)據(jù)
async deleteData() {
try {
const deleteIndex = 0;
await axios.delete('http://localhost:3000/api/data', {
data: { index: deleteIndex }
});
await this.getData();
console.info('刪除后',this.info );
} catch (error) {
console.error('刪除數(shù)據(jù)失敗:', error);
}
}
},
};
</script>運(yùn)行效果,從打印結(jié)果可以看到調(diào)用接口的時(shí)候數(shù)據(jù)發(fā)生了變化

end
到此這篇關(guān)于fetch,ajax,axios的區(qū)別以及使用的文章就介紹到這了,更多相關(guān)fetch,ajax,axios區(qū)別及使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Javascript&DHTML基礎(chǔ)知識(shí)
首先請(qǐng)下載JScript.chm這本手冊(cè),無論新手老手,有一本手冊(cè)是免不了的,特別是對(duì)于新手,如果你沒有空翻犀牛書,那么這本手冊(cè)將是你了解這門語言的首選。下面所講的大多數(shù),手冊(cè)上可以沒有提及,或提及很少的內(nèi)容。2008-07-07
完美實(shí)現(xiàn)八種js焦點(diǎn)輪播圖(下篇)
這篇文章主要介紹了完美實(shí)現(xiàn)八種js焦點(diǎn)輪播圖的具體代碼,基于完美運(yùn)動(dòng)框架move2.js實(shí)現(xiàn)的焦點(diǎn)錄播圖,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-07-07
微信小程序網(wǎng)絡(luò)封裝(簡(jiǎn)單高效)
這篇文章主要介紹了微信小程序網(wǎng)絡(luò)封裝(簡(jiǎn)單高效),微信小程序的網(wǎng)絡(luò)請(qǐng)求很便捷,直接調(diào)用就可以了。小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-08-08
JS實(shí)現(xiàn)DOM節(jié)點(diǎn)插入操作之子節(jié)點(diǎn)與兄弟節(jié)點(diǎn)插入操作示例
這篇文章主要介紹了JS實(shí)現(xiàn)DOM節(jié)點(diǎn)插入操作之子節(jié)點(diǎn)與兄弟節(jié)點(diǎn)插入操作,涉及JavaScript節(jié)點(diǎn)的創(chuàng)建、添加簡(jiǎn)單操作技巧,需要的朋友可以參考下2018-07-07
理解Javascript的caller,callee,call,apply區(qū)別
理解Javascript的caller,callee,call,apply區(qū)別...2007-03-03
優(yōu)化網(wǎng)頁之快速的呈現(xiàn)我們的網(wǎng)頁
優(yōu)化網(wǎng)頁之快速的呈現(xiàn)我們的網(wǎng)頁...2007-06-06
JavaScript實(shí)現(xiàn)跟隨鼠標(biāo)移動(dòng)的盒子
這篇文章主要為大家詳細(xì)介紹了JavaScript實(shí)現(xiàn)跟隨鼠標(biāo)移動(dòng)的盒子,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-01-01

