How to response status code to client?


#1

My server code is using PHP.

I want to response status 401 code to client:

http_response_code(401);

client code is:

$http.post(apiUrl, {data:data}).then(function (result){
        console.log('ok');
}, function(error){
        console.log(error);
});

but I get this error at client:

XMLHttpRequest cannot load http://xxx.com/xxx. Invalid HTTP status code 401
Object {data: null, status: 0, headers: function, config: Object, statusText: ""}

You can see the error status is 0 not 401. So I can’t use ‘interceptors’ catch this error status code.
How to make the error status code is correct response from the server with php?

NEW:
I found GET method can get right status code.but POST will not.

Object {data: "", status: 401, headers: function, config: Object, statusText: "Authorization Required"}

#2

I’m assuming this is happening when you are running in an emulator or device?

If i’m right i think the problem might be solved if you install the cordova whitelist plugin: https://github.com/apache/cordova-plugin-whitelist


#3

Thanks jawache, but I have the cordova whitelist plugin. These is it after start a project.


#4

Is this in the browser? Or when running on an emulator/device?


#5

i used chrome browser. GET($http.get) method can got correct status code. POST($http.post) method can’t get it.


#6

Ok if it’s just POST and not GET and it’s in the browser, that strongly hints to me that this is a CORS security issue. Does it work as you suspect when you run it on a device?


#7

I am not sure how about on a device. I have changed my solution.
I give up response http status code instead of my own error code.
Server will response the json. {‘ret’:1, ‘errcode’: 101}