首页 > 解决方案 > http请求仅在实际部署在服务器上时才花费太多时间

问题描述

我正在尝试通过“jquery ajax”在首页上向我的服务器发出 POST 请求,然后使用来自前面的数据向我的服务器上的外部服务器发出 POST 请求。使用我从外部请求获得的最终响应,我想使用 ajax 成功函数将新数据呈现到我的前面。它似乎在本地服务器上运行良好,但是当我使用 heroku 或 azure 部署这个项目时,整个过程需要 1000~2000ms 并且似乎根本无法运行。我的代码有什么问题?

我正在尝试构建一些检测系统,如果想要的课程有空缺,它会通知用户。所以我让用户选择一个班级,同时我通过向学校服务器发出的 POST 请求调用一个函数来检查该班级是否有空缺。

//index.html

//in front page, when user pick a course to start observing, I send POST to my server
function scanEmpty(data,cn,elem){
            $.ajax({
                url: './getLeftSeat',
                crossDomain: true,
                type: 'POST',
                data: data+`&cn=${cn}`,
                success: function (data) {
                    alert('got!')
                }
            })
        }
//app.js

// when I get POST from my server I call scanEmpty()
app.post('/getLeftSeat', async (req,res) => {
  scanEmpty(qs.stringify(req.body), req.body["cn"], () => {res.json({success: true})})
})

// and that is like this
const scanEmpty = async(data, CN, cb) => {
    if(await parseGetLeftSeat(await getData(data), CN)) cb()
    else {
        await scanEmpty(data,CN,cb)
    }
}

// send POST to school server and get response using axios
async function getData(data) {
    return await axios.post(school_server_url, data, {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'});
}

// it's just parsing and get data that I want
const parseGetLeftSeat = async (res, CN) => {
    return new Promise((resolve, reject) => {
        const $ = cheerio.load(res.data);
        $("#premier1 > div > table > tbody > tr > td").each((i, e) => {
            if (e.firstChild && e.firstChild.data == CN && e.next) {
                const tmp = e.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.next.firstChild.data.split('/')
                resolve(Number(tmp[1].trim()) - Number(tmp[0].trim()) < 1 ? false : true)
            }
        })
    })
}

它工作正常,但实际在部署服务器上需要 1000~2000 毫秒,而在本地服务器上需要 100~200 毫秒。我测试了一些代码,看起来 axios.post() 就是一个。但即使我将其更改为 node-fetch,结果也是一样的。我真的不知道该怎么办。

标签: node.jsrequesthttp-postaxiosfetch

解决方案


推荐阅读