在节点.js中获取 http 状态代码

Get http status code in node.js

本文关键字:http 状态 代码 获取 节点 js      更新时间:2023-09-26

所以,我正在尝试获取传递给功能的URL的http状态代码。 到目前为止,我已经使用了请求模块,但问题是请求获取给定 URL 的所有内容,如果内容是大量数据,则速度很慢,但我只需要获取状态代码即可进行 if 语句。

request(audioURL, function (error, response) {
    if (!error && response.statusCode == 200) {
        queue.push({
            title: videoTitle, 
            user: message.author.username, 
            mention: message.author.mention(), 
            url: audioURL
        });
        bot.reply(message, "'"" + videoTitle + "'" has been added to the queue.")
    }
    else {
        bot.reply(message, "Sorry, I couldn't get the audio track for that video. HTTP status code: " + response.statusCode);
    }
});

这就是我到目前为止得到的.audioURL 是一个基本字符串,带有指向媒体文件的链接

http.request可以将options对象作为其第一个参数。使用类似这样的东西:

const options = {
    method: 'HEAD',
    host: 'example.com',
};
const req = http.request(options, (res) => {
    console.log(JSON.stringify(res.headers));
});
req.end();

问题是您需要将audioURL转换为其组件,以作为options的参数传递。我使用的是HEAD方法,该方法仅获取请求的标头。