node.js check if a remote URL exists

前端 未结 11 758
萌比男神i
萌比男神i 2021-02-05 04:28

How do I check to see if a URL exists without pulling it down? I use the following code, but it downloads the whole file. I just need to check that it exists.

ap         


        
11条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 05:03

    If you're using axios, you can fetch the head like:

    const checkUrl = async (url) => {
      try {
        await axios.head(fullUrl);
        return true;
      } catch (error) {
        if (error.response.status >= 400) {
          return false;
        }
      }
    }
    

    You may want to customise the status code range for your requirements e.g. 401 (Unauthorized) could still mean a URL exists but you don't have access.

提交回复
热议问题