最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

NestJS裝飾器實(shí)現(xiàn)GET請(qǐng)求

 更新時(shí)間:2024年10月27日 11:47:27   作者:不叫貓先生  
本文介紹了如何通過(guò)裝飾器實(shí)現(xiàn)GET請(qǐng)求,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

裝飾器實(shí)現(xiàn)GET請(qǐng)求

定義一個(gè)裝飾器 Get,用于在 Controller 類中裝飾 getList 方法,以便從指定的 url 發(fā)起一個(gè) GET 請(qǐng)求。然后根據(jù)請(qǐng)求的結(jié)果調(diào)用 getList 方法,并將響應(yīng)數(shù)據(jù)或錯(cuò)誤信息傳遞給它。

Get裝飾器

其中Get接收一個(gè) url 字符串作為參數(shù),返回一個(gè)裝飾器函數(shù),該函數(shù)接收 target(類的原型對(duì)象)、key(方法名)、和 descriptor(方法的描述符)。

使用 Axios 發(fā)起 GET 請(qǐng)求,如果請(qǐng)求成功,則調(diào)用 fnc(即 getList)并傳入響應(yīng)數(shù)據(jù)和一個(gè)狀態(tài)對(duì)象;如果請(qǐng)求失敗,則也調(diào)用 fnc,并傳入錯(cuò)誤信息和狀態(tài)對(duì)象。

import axios from "axios";
const Get = (url: string) => {
	return (target: Object, key: any, descriptor: PropertyDescriptor) => {
		console.log(key,descriptor)
		const fnc = descriptor.value;//將原方法 fnc 存儲(chǔ)在變量中。
		axios.get(url).then(res => {
			fnc(res, {
				status: 200,
				success: true
			})
		}).catch(e => {
			fnc(e, {
				status: 500,
				success: false
			})
		})
	}
}

Controller類

包含一個(gè)構(gòu)造函數(shù)和一個(gè)被裝飾的方法 getList。getList 方法在接收到數(shù)據(jù)后可以進(jìn)行相應(yīng)的處理,例如輸出數(shù)據(jù)到控制臺(tái)。

class Controller {
	constructor() { }
	@Get("https://maqib.cn/_next/data/NLsSYPIRJyj1wLXgylj6N/blog.json")
	getList(res: any, status: string) {
		// console.log(res.data)
	}
}

優(yōu)化上面代碼

import axios from "axios";

const Get = (url: string) => {
	return (target: Object, key: string | symbol, descriptor: PropertyDescriptor) => {
		const originalMethod = descriptor.value;

		descriptor.value = async function (...args: any[]) {
			try {
				const res = await axios.get(url);
				// 調(diào)用原始方法并傳遞結(jié)果和狀態(tài)
				return originalMethod.apply(this, [res, { status: 200, success: true }, ...args]);
			} catch (e) {
				// 處理錯(cuò)誤情況
				return originalMethod.apply(this, [e, { status: 500, success: false }, ...args]);
			}
		};
	};
}

class Controller {
	constructor() {}

	@Get("https://maqib.cn/_next/data/NLsSYPIRJyj1wLXgylj6N/blog.json")
	async getList(res?:any, status?: { status: number; success: boolean }) {
		if (status?.success) {
			console.log(res.data); // 正常響應(yīng)
		} else {
			console.error('Error:', res); // 錯(cuò)誤處理
		}
	}
}

// 測(cè)試控制器
const controller = new Controller();
controller.getList(); // 調(diào)用 getList 方法

到此這篇關(guān)于NestJS裝飾器實(shí)現(xiàn)GET請(qǐng)求的文章就介紹到這了,更多相關(guān)NestJS GET請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

最新評(píng)論

连江县| 封开县| 伊春市| 宝应县| 彩票| 宜君县| 论坛| 罗山县| 喀喇| 平舆县| 阿拉善盟| 萝北县| 广南县| 桐柏县| 永寿县| 乐清市| 林周县| 宣化县| 莱州市| 威远县| 莎车县| 崇明县| 新乡市| 扎囊县| 清水河县| 贵定县| 和田市| 资中县| 台东市| 云和县| 福建省| 黑水县| 若羌县| 三河市| 万荣县| 安徽省| 扎赉特旗| 宣恩县| 利津县| 塘沽区| 泽普县|