简体   繁体   English

使用 XMLHttpRequest 获取服务器中的文件存在

[英]Using XMLHttpRequest to get file existence in the server

I have this code to check if there is a file with the given URL in the server or not.我有这段代码来检查服务器中是否存在具有给定 URL 的文件。 it returns true if there is a file and false if else...如果有文件则返回true,否则返回false...

The issue is if there is not a file, in the chrome's console I can see a 404 error which I expect because the given URL doesn't exist But:问题是如果没有文件,在 chrome 的控制台中我可以看到一个 404 错误,因为给定的 URL 不存在但是:

  • I wonder if this error will affect the execution of the whole code and the code quality?!不知这个错误会不会影响整个代码的执行和代码质量?!

  • How to remove the error if there is any solution?如果有任何解决方案,如何消除错误?

 // Check if file exist in the server function fileExist(url) { return new Promise((resolve) => { const xhr = new XMLHttpRequest(); xhr.open('HEAD', url, true); xhr.onload = function () { return resolve(xhr.status==200) }; xhr.onerror = function () { return resolve(xhr.status==200) }; xhr.send(); }); }

The only problem I can see is that your function treats any error as the file not existing.我能看到的唯一问题是您的 function 将任何错误视为文件不存在。 You should check specifically for xhr.status == 404 in the onerror function.您应该专门检查onerror function 中的xhr.status == 404 Anything else could be a server failure, network error, etc. and should trigger an error handler.其他任何事情都可能是服务器故障、网络错误等,并且应该触发错误处理程序。

A better way to do this would be to have a server script that checks whether the file is there.一个更好的方法是使用一个服务器脚本来检查文件是否存在。 Make an AJAX request to that script, and it can return a simple true/false response.向该脚本发出 AJAX 请求,它可以返回简单的true/false响应。 But this also has more overhead.但这也有更多的开销。

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

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