How to get correct $http error code, instead of -1? - angularjs

I use $http to retrieve data from server. In case error happen, all statusCode = -1. I cannot get correct errorCode to handle in client. I don't have permission to update server code.
$http(options).then(function (response) {
if (response.status === 200) {
resolve(response.data);
} else {
exceptionHandler(response);
}
}, function (error) {
exceptionHandler(error);
});
console.log is put on exceptionHandler function.
Please help me get correct error code. Many thanks.

In the responses you have shown, the 404 error is available as error.status but the other two responses were denied access by your browser when it performed the preflight OPTIONS request.
In that case the browser returns a status of -1 to indicate that the request was aborted. There is no HTTP status code for your request because it was never sent. The status 500 shown in the console log is not made available to any javascript code.
You should handle a status of -1 as indicating that no response was received from the server, either because it was never sent (this case), or because it was sent but timed out.

Related

HTTP request is aborted after response write in Golang

I have a server in Go that handles the files upload. It is a legacy code so I can't touch it so much.
The server should interrupt the upload if it detects some errors in the request header and it should return a message to the client that something is gone wrong.
The handler function is something like the following:
func(w http.ResponseWriter, r *http.Request) {
// Check the header. Could be more than one.
if r.Header.Get("key") == "not as expected" {
w.WriteHeader(500)
w.Write("key is wrong")
return
}
//handle the file upload
}
The header check is only an example to show the problem
The server closes the connection after Write and return from the function even if the request is not completed (file received).
On the client-side (Java) when I make a request with the key with a wrong value and the file to upload as a body, I get a broken pipe exception and It can't handle the response correctly.
Actually I can't touch the client-side code.
There is way on server side to wait until the request ends before closing the connection?
The "broken pipe" error¹ seen on the Java client suggests the client insists on sending the payload (body) of its request before attempting to read the response from the server.
In HTTP/1.1 (and 1.0), the client is correct: nothing in the spec says the client has to expect the server to respond before the whole request — that is, the header and the body, if any, — gets submitted.
In your particular case, the simplest approach is to pipe the clien's body to nowhere and after that respond with an error. One idiomatic approach is using io/ioutil.Discard type:
func(w http.ResponseWriter, r *http.Request) {
// Check the checksum header
if r.Header.Get("key") == "not as expected" {
_, err := io.Copy(ioutil.Discard, r.Body)
if err != nil {
// The client went away.
// May be log something, then bail out.
panic(http.ErrAbortHandler)
}
w.WriteHeader(500)
w.Write("key is wrong")
return
}
//handle the file upload
}
net/http.ErrAbortHandler may be used to tell the HTTP server library code the request should not be carried out the normal way.
By the way, responding with 5xx to an ill-formed client request is incorrect, you should have been using 4xx instead. But it's a legacy code, so just take this as a hint for future developments.
¹ See EPIPE in the send(2) manual page.

Uncaught (in promise) Error: Request failed with code 405 POST AXIOS

I am trying to post data in my database but every time I do try to dod it I get a 405 error. Also python has an error saying that I am submitting an empty list. Please point me in the right direction to solve this problem.
const axios = require('axios')
let URL = 'http://127.0.0.1:5000/Walls/saveComments'
let HEADERS = { 'Content-Type': 'application/json' }
let data = {
'post': post,
'time': time
}
axios.post(URL,data, HEADERS)
.then(function (response) {
console.log(response);
})
// Axios Call to Save A Post in Backend
The HTTP 405 error means that the server does not allow the HTTP request method that the client sent.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
The HTTP method you're using in the code example you shared is POST. Therefore, it seems that your server does not accept POST requests.
In order to fix this, either change the request method to something that is supported, or change the server to allow POST requests.

Handle error codes (401, 403) with Restangular

I am building an app using Restangular. I would implement in one place handling of errors like 401, 403, 500 etc in a response interceptor.
This is what I wrote:
RestangularProvider.setResponseExtractor(function(response, operation, what, url) {
switch(response.meta.code) {
case 200:
// Handle 200
break;
case 401:
// Redirect to login
break;
/* ... */
default:
break;
}
}
What actually happens it's that the 200 is correctly seen but this method is not hit at all for the 401.
The JSON I get from server side it is formatted like this for successful responses:
{"meta":{"apiVersion":"0.1","code":200,"errors":null},"response":{"response":"value"}}
and
{"meta":{"apiVersion":"0.1","code":401,"errors":[{"code":401,"message":"Unauthorized"}]},"response":null}
for errors. The response header contains the Status Code:401 Unauthorized as well.
What am I doing wrong?
401 and any error code will hit the errorInterceptor, not the responseInterceptor. responseInterceptor is only called with successful responses!

Backbone - Handle empty response from the server

I use fetch to retrieve my models from the server. It works great when I have data in my DB but how to handle an empty response send by the server to the client ?
For example if no data have been already saved by the user the server send a http 200 response with an empty array and backbone triggers an error callback but I just want to inform the user that there is no data saved in DB. In this case an empty response just means there is no model to load and I don't want to create any model with the response.
Here is the code I use :
app.plans.fetch({
success: function(data) {
app.Notifications.updateMessages({text: "Plans loaded."});
},
error: function (){
app.Notifications.updateMessages({text: "Error."});
}
});
How the server can indicate that it's all right but there is just no data ?
If you are responsible for back-end and you can change response behavior you should use http status 204 for empty content response instead of 200
this should help
If server responds with the 200 it shouldn't trigger an error callback. It's weird.
Could you please add the example of the server response?
Also success and error callbacks take the following options as arguments: (collection, response, options)

How server responds to device for GET request for updating a pass

For getting the Latest Version of a Pass, GET request to webServiceURL/version/passes/passTypeIdentifier/serialNumber. What server do to respond to this request ? This is code I use:
if (strtoupper($_SERVER['REQUEST_METHOD']) === "GET" && $request[3]==='passes'){
$passTypeID = $request[4];
$serial = $request[5];
$auth_key = str_replace('ApplePass ', '', $headers['Authorization']);
}
From the Apple Docs.
If request is authorized, return HTTP status 200 with a payload of the pass data.
If the request is not authorized, return HTTP status 401.
Otherwise, return the appropriate standard HTTP status.
The "payload of the pass data" means the .pkpass bundle.

Resources