一文詳解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ù))的核心。通過(guò) XMLHttpRequest,可以在不刷新整個(gè)頁(yè)面的情況下與服務(wù)器交換數(shù)據(jù)并更新部分網(wǎng)頁(yè)內(nèi)容。而jquery的$.ajax簡(jiǎn)化了XMLHttpRequest的使用。
區(qū)別
ajax:是最早用于實(shí)現(xiàn)異步數(shù)據(jù)交互的技術(shù),出現(xiàn)時(shí)間較早。兼容性非常好,能在所有主流瀏覽器(包括一些較舊版本的瀏覽器)中使用。
fetch:是 ES6 引入的新的 API,現(xiàn)代瀏覽器基本都支持,但在一些舊版本瀏覽器中需要使用 polyfill 來(lái)實(shí)現(xiàn)兼容。
axios:是一個(gè)基于promise的 HTTP 客戶端,用于瀏覽器和 Node.js。由于是第三方庫(kù),使用時(shí)需要引入,不過(guò)它通過(guò)內(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中間件來(lái)配置跨域,安裝命令
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 中間件,允許來(lái)自 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)聽(tīng)指定端口 app.listen(port, () => { console.log(`服務(wù)器正在運(yùn)行,訪問(wè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是第三方庫(kù),在使用前需要安裝,命令
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 中間件,允許來(lái)自 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)聽(tīng)指定端口 app.listen(port, () => { console.log(`服務(wù)器正在運(yùn)行,訪問(wè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ù)接口來(lái)獲取最新的數(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獲取URL參數(shù)常見(jiàn)的4種方法
對(duì)于獲取URL參數(shù),有很多種方法可以實(shí)現(xiàn),下面這篇文章主要給大家介紹了關(guān)于JavaScript獲取URL參數(shù)常見(jiàn)的4種方法,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-07-07JS.getTextContent(element,preformatted)使用介紹
JS.getTextContent獲取標(biāo)簽的文字想必大家并不陌生吧,下面為大家介紹下具體的使用方法,感興趣的朋友可以參考下2013-09-09詳解JavaScript時(shí)間處理之幾個(gè)月前或幾個(gè)月后的指定日期
本篇文章主要介紹了JavaScript時(shí)間處理之幾個(gè)月前或幾個(gè)月后的指定日期 ,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2016-12-12腳本分析、壓縮、混淆工具 JSA新版本發(fā)布,壓縮效率提高大約10%
腳本分析、壓縮、混淆工具 JSA新版本發(fā)布,壓縮效率提高大約10%...2007-05-05