捕获Javascript中的jQuery $ .ajax错误(或浏览器控制台错误)

时间:2020-06-12 11:18:00

标签: javascript jquery ajax browser-console

这是一个基本的jQuery $ ajax函数,我故意在其中调用假端点;

const URL_RESTEndpoint = "http://localhost/api/MyEndpointIntentionalNotExist"
$.ajax(
{
    url: URL_RESTEndpoint,
    method: "PATCH",
    //etc...     
})
.done( (data, textStatus, jqXHR) => {
    //do stuff with data...
})
.fail( (jqXHR, textStatus, errorThrown) => {
    //do stuff with error params...
})
.always ( function (data_xhr, textStatus) {
    console.log(textStatus);
}

上面的代码运行时,在(Chrome的)浏览器控制台上,它会打印出一个很长的错误字符串:

"Access to XMLHttpRequest at 'http://localhost/api/MyEndpointIntentionalNotExist' 
from origin 'http://localhost:3000' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' 
header is present on the requested resource."

好的。精细。但是我想以某种方式在我的js代码中捕获上述控制台错误字符串,这可能吗?

我已经检查了所有。$ ajax对象或参数;最好的办法是将文字字符串“ error”显示为错误。认真吗?!

更新: 感谢注释器和链接,显然这是捕获JS中的CORS错误的安全漏洞。 无需回答,我投票结束了问题,但将来可能会对某人有所帮助。

0 个答案:

没有答案