JQuery问题:服务器已开启,但Ajax请求返回状态码0
我在检查服务器数据库中是否存在重复邮箱时遇到问题:服务器明明处于开启状态,且直接用浏览器访问请求URL能正常获取结果,但通过jQuery Ajax发送请求却始终返回状态码0。相关代码如下:
if (input == email.find(".form_input").val()) { emailChecking = true; $.ajax({ url: "https://localhost:8888/check?target=" + input, async: true, type: "GET", dataType: "text", success: (data) => { console.log(data); if (emailChecking == true) { emailChecking = false; inputField(email, error); } }, error: (request, status, errorLine) => { if (emailChecking == true) { emailChecking = false; error = "cannot check email - code " + request.status; inputField(email, error); } } }); }
以下是可能的原因和解决办法:
跨域限制问题:如果前端页面和后端服务不在同一域名/端口下(比如前端跑在
http://localhost:3000,后端是https://localhost:8888),浏览器会触发CORS校验。直接在地址栏访问GET请求不会触发跨域检查,但Ajax请求会严格校验。
解决:后端需要配置CORS响应头,比如添加Access-Control-Allow-Origin: *(开发环境临时用,生产环境要指定具体域名),同时确保OPTIONS预检请求能被正确处理。请求被中途中止:如果输入框内容快速变化,前一个Ajax请求还没完成就发起了新请求,旧请求会被浏览器中止,返回状态码0。另外页面跳转、刷新也会导致请求中止。
解决:发起新请求前先取消上一个未完成的请求,用$.ajax()返回的jqXHR对象的abort()方法:let pendingEmailCheck; // 全局保存上一个请求对象 if (input == email.find(".form_input").val()) { emailChecking = true; if (pendingEmailCheck) { pendingEmailCheck.abort(); // 取消未完成的请求 } pendingEmailCheck = $.ajax({ url: "https://localhost:8888/check?target=" + input, async: true, type: "GET", dataType: "text", success: (data) => { console.log(data); if (emailChecking == true) { emailChecking = false; inputField(email, error); } }, error: (request, status, errorLine) => { if (emailChecking == true) { emailChecking = false; error = "cannot check email - code " + request.status; inputField(email, error); } }, complete: () => { pendingEmailCheck = null; // 请求完成后清空对象 } }); }HTTPS证书未信任:后端用了HTTPS,但如果是自签名证书,浏览器地址栏访问时你可能手动确认了信任,但Ajax请求会直接拒绝,返回状态码0。
解决:在浏览器中导入并信任该自签名证书,或者开发环境暂时改用HTTP测试。URL参数未编码:邮箱包含@、+、.等特殊字符时,直接拼接在URL中会导致格式错误,浏览器地址栏会自动编码,但Ajax请求不会。
解决:用encodeURIComponent()对邮箱参数编码:url: "https://localhost:8888/check?target=" + encodeURIComponent(input),
内容的提问来源于stack exchange,提问作者gmma

