From 60022e4c23c961062297fc35234f2998ec908db9 Mon Sep 17 00:00:00 2001 From: Toly Date: Sun, 22 Sep 2024 21:16:19 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=A7=20Add=20try=20catch.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- routes/index.js | 39 ++++++++++++++++++++++----------------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/routes/index.js b/routes/index.js index 5ea585f..9086254 100644 --- a/routes/index.js +++ b/routes/index.js @@ -41,24 +41,29 @@ router.post("/translation/content/", async function (req, res, next) { console.log(`Original content: ${textToBeTranslated}`); const url = `https://dict.youdao.com/result?word=${textToBeTranslated}&lang=en`; let dicList = []; - const a = await axios(url); + try { + const a = await axios(url); - const $ = cheerio.load(a.data); - const dictBook = $(".basic .word-exp"); - let phonetic = ""; - const yinBiao = $(".phone_con .phonetic"); - yinBiao.each((index, element) => { - phonetic += $(element).text() + " "; - }); - dictBook.each((index, element) => { - const ciXing = $(element).find(".pos"); - const zh = $(element).find(".trans"); - dicList.push({ pos: $(ciXing).text(), zh: $(zh).text() }); - }); - const dictBookSecond = $(".dict-module .trans-container .trans-content"); - dicList.push({ pos: "", zh: $(dictBookSecond).text() }); - console.log(dicList); - res.json(generateResponse({ dicList, phonetic })); + const $ = cheerio.load(a.data); + const dictBook = $(".basic .word-exp"); + let phonetic = ""; + const yinBiao = $(".phone_con .phonetic"); + yinBiao.each((index, element) => { + phonetic += $(element).text() + " "; + }); + dictBook.each((index, element) => { + const ciXing = $(element).find(".pos"); + const zh = $(element).find(".trans"); + dicList.push({ pos: $(ciXing).text(), zh: $(zh).text() }); + }); + const dictBookSecond = $(".dict-module .trans-container .trans-content"); + dicList.push({ pos: "", zh: $(dictBookSecond).text() }); + console.log(dicList); + res.json(generateResponse({ dicList, phonetic })); + } catch (error) { + console.log(error); + res.json(generateResponse({ dicList: [], phonetic: "" })); + } }); router.post("/grab", async function (req, res, next) {