在 node.js 中获取 http 状态代码
Get http status code in node.js
所以,我正在尝试获取传递给函数的 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);
}
});
这就是我得到的 far.audioURL 是一个带有 link 到媒体文件的基本字符串
http.request
可以将 options
Object 作为其第一个参数。使用这样的东西:
const options = {
method: 'HEAD',
host: 'example.com',
};
const req = http.request(options, (res) => {
console.log(JSON.stringify(res.headers));
});
req.end();
问题是您需要将 audioURL
变成它的组件,作为 options
的参数传递。我正在使用 HEAD
方法,它只获取您请求的 headers。
所以,我正在尝试获取传递给函数的 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);
}
});
这就是我得到的 far.audioURL 是一个带有 link 到媒体文件的基本字符串
http.request
可以将 options
Object 作为其第一个参数。使用这样的东西:
const options = {
method: 'HEAD',
host: 'example.com',
};
const req = http.request(options, (res) => {
console.log(JSON.stringify(res.headers));
});
req.end();
问题是您需要将 audioURL
变成它的组件,作为 options
的参数传递。我正在使用 HEAD
方法,它只获取您请求的 headers。