How can I elegantly handle devise's 401 status in AJAX?

后端 未结 7 1964
庸人自扰
庸人自扰 2020-12-23 18:53

With devise one uses before_filter :authenticate_user! to restrict access to authenticated users only.

When an unauthenticated

7条回答
  •  温柔的废话
    2020-12-23 19:54

    As of Rails 5.1 and the new rails-ujs, all custom events return only one parameter: event. In this parameter, there is an additional attribute detail which contains an array of extra parameters. The parameters data, status, xhr have been bundled into event.detail. So handling the 401 error in ajax with the ajax:error event becomes:

    document.body.addEventListener('ajax:error', function(event) {
      var detail = event.detail;
      var response = detail[0], status = detail[1], xhr = detail[2];
      if (xhr.status == 401) {
        // handle error
      }
    })
    

提交回复
热议问题