简体   繁体   English

检查 URL 是否存在并链接到音频文件

[英]Check to see if URL exists and is linked to audio file

I've written a test to validate that an audio (MP3, WAV) is in the correct URL format.我编写了一个测试来验证音频(MP3、WAV)是否采用正确的 URL 格式。

Now I want to check two things:现在我想检查两件事:

  1. that the URL exists URL 存在
  2. make a head request to make sure that the URL is linking to an audio file发出头部请求以确保 URL 正在链接到音频文件

How do I do that?我怎么做? I've yet to find any good JavaScript examples on making head requests.我还没有找到任何关于提出头部请求的好的 JavaScript 示例。

 // The test being performed if (result.onClose === true) { if(UtilService.isValidUrl(result.url) && UtilService.isValidAudioUrl(result.url)) { console.log('url is valid') } } // In UtilService static isValidUrl(urlToCheck: string) { let url; try { url = new URL(urlToCheck); } catch (_) { return false; } return url.protocol === 'http:' || url.protocol === 'https:'; } // Unsure how to perform the check here static isValidAudioUrl(urlToCheck: string) { const xhr = new XMLHttpRequest(); xhr.open("HEAD", urlToCheck); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { console.log(xhr.status); console.log(xhr.responseText); }}; xhr.send(); // I'd like it to return a boolean value of true or false in isValidAudioUrl if the response header indicates the media type of the URL is audio and exists return false; }

I think your audio URL validation function may look like this.我认为您的音频 URL 验证 function 可能看起来像这样。 The idea is to check the Content-type response header.这个想法是检查Content-type响应 header。 For audio files it usually starts with audio (eg audio/mpeg )对于音频文件,它通常以音频开头(例如audio/mpeg

function isValidAudioUrl(urlToCheck) {
  return fetch(urlToCheck, { method: 'HEAD', mode: 'no-cors' })
    .then(res => res.ok && res.headers.get('content-type').startsWith('audio'))
    .catch(err => console.log(err.message));
}

// In your code
console.log('validating');

isValidAudioUrl('https://<YOUR_URL>.mp3')
.then(result => console.log(result));

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

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