gpt4 book ai didi

javascript - 发送服务器请求时 api 返回服务器错误

转载 作者:行者123 更新时间:2023-12-01 00:51:32 24 4
gpt4 key购买 nike

我有一个 Node js 应用程序,我正在从网站上抓取数据以获取数据。我已将 Node api 部署到 azure。我正在从 api 获取不同日期的数据。当所选日期有数据时,API 可以正常工作。但当所选日期没有数据时,它会返回服务器错误。返回服务器错误后,当我选择包含数据的不同日期时,它不会返回任何数据。为什么会发生这种情况?这是我现在的代码:

const express = require('express');
const request = require('request');
const cheerio = require('cheerio');
const router = express.Router();

router.get('/:id?', (req, res, next) => {
let url = 'https://scrapingwebsite/' + req.params.id

let resultTable = []
let resultTable2 = []
let resultTable3 = []
let fr = []
let sc = []
let resultTable4 = []
let resultTable5 = []
let resultTable6 = []
let resultTable7 = []
let resultTable8 = []
let resultTable9 = []
let mdate = []
let mdraw = []
request(url, (error, response, html) => {
if (!error && response.statusCode == 200) {
const $ = cheerio.load(html);
$('.resultTable').each((i, el) => {
let resultTop = $(el).find('.resultTable2').text()
resultTable2.push(resultTop)


let resultBottomFirst = $(el).find('.resultbottom').text()
resultTable4.push(resultBottomFirst)


let resultBottomSecond = $(el).find('.resultbottom').text()
resultTable7.push(resultBottomSecond)
})
let first = resultTable2[0].toString()
console.log(resultTable2[0])
let date = first.slice(18, 28)
let draw = first.slice(34, 49)
let firstPrize = first.slice(61, 65)
let firstP = ['1st Prize',firstPrize ]
let secondPrize = first.slice(77, 81)
let secondP = ['2nd Prize',secondPrize ]
let thirdPrize = first.slice(93, 97)
let thirdP = ['3rd Prize',thirdPrize ]
resultTable = resultTable2[0]
resultTable3.push(firstPrize, secondPrize, thirdPrize)
fr.push(resultTable3)
sc.push(firstP,secondP,thirdP)

mdate.push(date)
mdraw.push(draw)

resultTable5 = resultTable4[0]
let middle = resultTable4[0].toString()
let resultBottom1 = middle.match(/.{1,4}/g).slice(0,5)
let resultBottom2 = middle.match(/.{1,4}/g).slice(5,10)
let resultBottom3 = middle.match(/.{1,4}/g).slice(10,13)
resultTable6.push(resultBottom1,resultBottom2,resultBottom3)

resultTable8 = resultTable7[0]
let last = resultTable7[0].toString()
let resultBottom4 = last.match(/.{1,4}/g).slice(13,18)
let resultBottom5 = last.match(/.{1,4}/g).slice(18,23)
resultTable9.push(resultBottom4, resultBottom5)
}

res.status(200).json({
date: mdate,
draw: mdraw,
magnum: fr,
magnum2: sc,
special: resultTable6,
consolation: resultTable9
});
});

});

module.exports = router;

最佳答案

我猜当没有找到数据时,您的 resultTable2、resultTable4、resultTable7 会变为 null,并且 toString() 操作会因此失败。这就是为什么你的 api 无法返回数据并卡住的原因。

关于javascript - 发送服务器请求时 api 返回服务器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56929129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com