weixin_33709364 2014-11-02 01:10 采纳率: 0%
浏览 6443

如何处理CORS错误代码?

Edit: I just realized this is a duplicate of Recommended solution for AJAX, CORS, Chrome & HTTP error codes (401,403,404,500), and he tried the idea I propose at the end. But I can't tell if he succeeded (dud user?), and no one else has posted a solution or even a comment, so I think it's worth fishing for new answers.

Problem:

  • I send a properly-executed (edit: IMproperly-executed. End of story...) CORS request.
  • The server receives the request and attempts to process it.
  • The server returns an error response, for example a 422 Unprocessable Entity, along with JSON information about the errors. The idea is that my app could receive this error information and handle it appropriately in the UI.
  • The browser blocks my error handler from getting the response content, or even getting the status code.

Showing that the browser received the 401 status code but treated it as a CORS security error:

Status Code 401

The response object, showing that my code cannot access the response data (data: "", status: 0):

Obscured Response Object

How have other people handled this limitation? My best guess right now is to hijack an HTTP "success" code (2XX) as an error code, and then include the error information in the response. This prevents me from using the ajax error handlers in a normal way, but I'm handling this as a global ajax filter anyway, so this filter would capture the deviant success code and trigger the error handlers instead.

  • 写回答

3条回答 默认 最新

  • weixin_33674437 2019-08-04 05:52
    关注

    Very late answer but in case someone wants to check whether an error occurred while sending an XMLHttpRequest and then take appropriate actions (on the CLIENT side), then this is a quick workaround:

    try{
        request.send();
    }catch(err){
        if(e.toString().startsWith("NetworkError")){
            //pasre the string to check error code
            //and take appropriate actions
        }
    }
    

    This is needed because the onreadystatechange function doesn't get executed when a NetworkError occurs and, in fact, the whole script is terminated.

    评论

报告相同问题?

悬赏问题

  • ¥200 csgo2的viewmatrix值是否还有别的获取方式
  • ¥15 Stable Diffusion,用Ebsynth utility在视频选帧图重绘,第一步报错,蒙版和帧图没法生成,怎么处理啊
  • ¥15 请把下列每一行代码完整地读懂并注释出来
  • ¥15 pycharm运行main文件,显示没有conda环境
  • ¥15 寻找公式识别开发,自动识别整页文档、图像公式的软件
  • ¥15 为什么eclipse不能再下载了?
  • ¥15 编辑cmake lists 明明写了project项目名,但是还是报错怎么回事
  • ¥15 关于#计算机视觉#的问题:求一份高质量桥梁多病害数据集
  • ¥15 特定网页无法访问,已排除网页问题
  • ¥50 如何将脑的图像投影到颅骨上