简体   繁体   English

如何检查 URL 是否存在?

[英]How can I check to see if a URL exists or not?

I'm trying to make a Discord bot that will automatically post a message when a new chapter of a manga is posted.我正在尝试制作一个 Discord 机器人,它会在发布漫画的新章节时自动发布一条消息。 I have never done JavaScript before, and I have no idea what code one would use to do that.我以前从未使用过 JavaScript,我不知道人们会使用什么代码来做到这一点。 The URL ends in "/en/0/[Chapter Number]", and nothing else in the entire URL changes, so all the bot would have to do is check one number above the one posted, then when that link doesn't lead to a 404 anymore it posts the message on Discord and updates the chapter number it's checking. URL 以“/en/0/[Chapter Number]”结尾,并且整个 URL 中的其他任何内容都没有更改,因此机器人所要做的就是检查发布的数字上方的一个数字,然后当该链接不引导时再到 404,它会在 Discord 上发布消息并更新它正在检查的章节编号。 Any help you can give is appreciated.感谢您提供的任何帮助。

EDIT:编辑:

I am using Node.js and Visual Studio Code, if that matters如果重要的话,我正在使用 Node.js 和 Visual Studio Code

You can use Node's https built-in module to determine the status code of the page.您可以使用 Node 的https内置模块来确定页面的状态代码。 If the status code is 200 , you would know the page exists.如果状态代码是200 ,您就会知道该页面存在。 You could also check for other status codes ( 404 , like you mentioned) that you see fit.您还可以检查您认为合适的其他状态代码( 404 ,就像您提到的那样)。

const https = require('https')

https.get('https://discordapp.com/', res => {
    if(res.statusCode === 200) {
        console.log('Page exists!')
    }
})

You probably want to make a request to the url in order to check the response code.您可能想要向 url 发出请求以检查响应代码。 If you are working on a discord bot, you are probably using node, in that case you want to pick a request library and look up the documentation for using it:如果您正在使用 discord bot,您可能正在使用 node,在这种情况下,您想选择一个请求库并查找使用它的文档:

Here are some of them:这里是其中的一些:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM