5

I'm trying to return 401 response status in my AngularJS app. But in console that I see, it returns -1

What I use in php:

header("HTTP/1.1 401 Unauthorized");
http_response_code(401);

Also in codeigniter:

$this->output->set_header('HTTP/1.1 401 Unauthorized');
$this->output->set_status_header(401, "my status text");

enter image description here

It works fine in status codes like: 200 , 205, 206 etc.

enter image description here

Any idea?

Vahid Najafi
  • 4,654
  • 11
  • 43
  • 88

1 Answers1

3

You are making a cross origin request from XMLHttpRequest.

In a simple case, this means that the server has to grant permissions to the JavaScript before the browser will give the data to the JavaScript.

This is not a simple case. You are making a complex request which requires preflight authorisation.

Before making the POST request you want to make, the browser is making an OPTIONS request asking for permission.

The server is responding to the OPTIONS request with a 401 response. The error message tells you this explicitly:

Response for preflight has invalid HTTP status code 401

The browser is then refusing to make the POST request at all.

Consequently the status of the POST request is -1.

You need to respond to the OPTIONS request with a 200 status (and appropriate CORS permissions headers). Then the browser will make a POST request (which you can reject with a 401 if you like).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    (A lesson here is that when you have four lines of output in the console, you shouldn't focus your attention solely on the *last* one) – Quentin Sep 19 '16 at 09:54
  • Woow! Thank you. You're right. As mentioned in your link : `It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)` , when I cleaned this header `$http.defaults.headers.common.Authorization`, I could able to get **401** response code. So what I can I do? – Vahid Najafi Sep 19 '16 at 11:17
  • 1
    @vahidnajafi — As I said, change the server side code so it always responds OK (with appropriate CORS headers) to the OPTIONS request. – Quentin Sep 19 '16 at 11:28
  • 1
    Thank you so much. You saved my day. Finally I did what you said in server with this: `if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { http_response_code(200); exit(); }` – Vahid Najafi Sep 19 '16 at 11:35