XMLHttpRequest检测404(未找到)

jca*_*314 2 javascript

如果URL正确(file.dat存在),这很好用(文件长度匹配).如果它错了,我会看到一个非常小的文件长度,我不会看到xhr.onerror.

如何检测到URL不正确?

var xhr = new XMLHttpRequest()
xhr.responseType = "blob"
xhr.onload = ()=> {
    var reader = new FileReader()
    reader.onload = evt => {
        var contents = new Buffer(evt.target.result, 'binary')
        console.log('file len',contents.length) 
    }
    reader.readAsBinaryString(xhr.response)
}
xhr.addEventListener("error", () => { console.error('xhr.onerror',e) })
xhr.open("GET", "file.dat")
xhr.send()
Run Code Online (Sandbox Code Playgroud)

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

我确实看到控制台中的堆栈跟踪指向 xhr.send() GET http://localhost:8080/file.dat 404 (Not Found)

尝试捕获open和send都没有捕获任何异常.

文件由WebpackDevServer提供(我希望这不应该重要).

Jua*_*des 6

您可以检查响应对象状态.

// Not using arrow function because I don't want the lexical `this`
xhr.onload = function() {
    if (this.status === 404) {
       // not found, add some error handling
       return;
    }
    var reader = new FileReader()
    reader.onload = evt => {
        var contents = new Buffer(evt.target.result, 'binary')
        console.log('file len',contents.length) 
    }
    reader.readAsBinaryString(xhr.response)
}
Run Code Online (Sandbox Code Playgroud)

感谢https://developer.appcelerator.com/question/129410/xhr-request-cant-check-for-error-for-404-page-or-other-errors