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

如何处理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.

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决