Express: Is it necessary to respond with status 200? - javascript

Is it necessary to respond with a status 200 code or is it the default behavior?
response.json({
status: 'OK',
});
vs.
response
.status(200)
.json({
status: 'OK',
});
When I hit the route in my browser, I get a 200 response in both cases
By now, I only use status code for other responses than 200 (e.g. 404, 500)

The Express response object wraps the underlying Node.js response object. In Node.js, if you don't set a response, it will always be 200. Express operates the same way for most requests. It will also automatically handle setting some error response codes for you depending on if and where an error was thrown.
Further, Express will set the response code for you on certain types of routes, for example, if you've defined a redirect, it will automatically set the 302 code for you.

Related

NodeJS server - client behaves differently for response status 500, depending on response body

I have set up a NodeJS server, listening on localhost:3000, and I am testing it with Chrome browser.
When the response status code is 500:
If the response body is empty, then the client shows:
This page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500
If the response body is not empty, then the client (surprisingly) shows it with no error
Here is a sample code to reproduce this:
let http = require("http");
let state = true;
let server = http.createServer(async function(request, response) {
if (request.url == "/") {
response.statusCode = 500;
response.end(state ? "" : "data");
console.log(state);
state = !state;
}
});
server.listen(3000, async function(error) {
if (error)
return console.log(error);
console.log("server is listening");
});
To tell you the truth, I am not worried about how the browser displays it, because my real client is some other process in the system. But I want to make sure that this process receives the correct status code (500) even if I enclose some data in the response body.
So I'd like to know if there is something wrong in my code (i.e., if I am not allowed to send data along with status 500), or if it's just Chrome's default behavior.
According to this post and this discussion Chrome if displaying a "friendly" error page is server responded with error code without the body (earlier it was for less than 512 bytes in response) - that's why you see a different behavior.
In most cases you would send the custom error page along with the error code, to display it to user. So there's no need to show error if there's a custom page displaying it anyway.
And if you just need to validate the response headers there are special extensions to chrome that allows you to see it. For example there's HTTP Headers.
Also I suppose you could use some kind of debugging proxy, like for example fiddler to capture the traffic, and inspect the requests and responses.

Unable to call web-service from angularjs app

Unable to call post webservice from my application. following is the code.
var postLogin = "http://0.0.0.0:000/ddd/v1/login";
var loginvalue = {"email":"some#mail.com","password":"cbsjc6dw3bgjyfdgdKHGGDF="};
var config = {
headers: {
'Content-Type': 'application/json'
}
}
$http.post(postLogin ,loginvalue,config ).success( function(response) {
alert("response "+ response)
$scope.defer.resolve(response);
}).error(function(error){
alert("dddddd" + JSON.stringify(error));
})
If i write this code then it is returning as 400 error but if i use the postman application of google then i am getting the response without any error. So i am in confusion that whatever the code i have written is right or wrong. Hence i need to solve this issue.
Please go through the above image.
This usually happens when Client and Server are on different domains. The POST requests done by the client are first verified with a OPTIONS pre-flight check, to see if a POST would be possible. Sometimes, servers are configured to not allow OPTIONS request method. This will be the outcome of a pre-flight OPTIONS check, in such a case.
There is more information here - Why is an OPTIONS request sent and can I disable it?
Other resources for understanding the concept and helping us to configure the Response headers from the Server-side application are here:
https://medium.com/#praveen.beatle/avoiding-pre-flight-options-calls-on-cors-requests-baba9692c21a
https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
At the end of the day, if the Server is NOT configured to handle Cross-site requests, nothing can be done from the client-side.
Also, there are cases where the server does allow cross-site request, processes and send the response back to client, without the Access-Control-Allow-Origin header or with the Access-Control-Allow-Origin header, but not the same as the request origin or a wildcard "*". In such cases, browser stops processing the response, even when the call turns out to be in HTTP 200 OK Status.
Below is one such example, that I recently encountered while integrating with an external application.

Choosing a HTML status code for errors in Express apps

In my API if any query fails then what should be the response status code?
Example :
Grade.find({},function(err,grades) {
if (err)
res.status(500).json({error:err,message: 'Somthing went wrong please try again later'});
else
res.status(200).json({grades:grades});
});
Is 500 OK or should it be something else ?
TL;DR A 500 status is the closest thing to a 'one size fits all' error, but you can get into much deeper details.
According to the standards, you have plenty of choices :
5xx Server Error
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
510 Not Extended
You could also create your own 5xx status to differentiate between error types, just try to use numbers that are not defined for anything else.
Or stick to a 500 status and attach the original error code to your result :
res.status(500).json({error:err, code : err.code, message: 'Somthing went wrong please try again later'});
However, before answering with 5xx, you want to make sure that the error doesn't come from the client, by validating the data you receive. If the received data is invalid, use a 400 Bad Request code. If the issue is security related, use a 403 Not Authorized, etc...
According to http status codes you can use 5xx for server error and 4xx for client error.

RESTful alternative to 3xx responses for JavaScript based clients

Several our REST service needs to indicate that further action needs to be taken by the client to fulfill the request (very often that the response to the request can be found under another URI).
In general this is achieved by means of HTTP 3xx responses. However, in case of JavaScript based client the redirection is performed by the browser itself before the response can reach JavaScript code.
Basically what I need is a RESTful way to inform the client (JavaScript code) that the response can be found under another URI and let the client process such a response on its own.
I am thinking about two solutions:
HTTP 200 OK with the entity containing URI to follow. I do not like creating a whole entity carrying only URI. I would rather to achieve this via HTTP headers
HTTP 204 No Content response with the Location header containing the given URI. But here I am not sure if it is "REST compliant". Is it OK to combine HTTP 204 No Content with Location header that is used mainly in redirection (along with HTTP 3xx responses), or when a new resource has been created?
Or is there a better solution?
If I understand you correctly, you have a process, say of 5 steps. After step 5 there is some result prepared, to which you want to point your client, not via HTTP-3xx, but in a cleaner way.
I would suggest, that you make use of the link property in your JSON-response:
{
...
"links": [
...
"result": { "href": "/calculation/1234" }
...
]
}
Your client could take this answer and transform it to a simple link/button.
This is conforming with HATEOAS (Hypermedia As The Engine Of Application State), indicating, that the current state offers the result under a different location which is referenced.
Assuming you have a json response format, you could accept a request parameter like noredirect that when present sets the http response code to 200 and set the real response code in the returned object.
GET /some/resource
200 OK
{
status: 200,
…
}
GET /some/unknown/resource
404 Not Found
{
status: 404,
…
}
GET /some/unknown/resource?noredirect
200 OK
{
status: 404,
…
}

HTTP headers for AJAX/ denied authentication?

I would like to know what is best practice with AJAX authentication process.
When authentication is valid I return HTTP header 200 with response "ok"
What HTTP header do I need to send from server if authentication is NOT valid.
Do I need to set HTTP header to code 500 (ERROR)
or leave it on 200 and implement logic which checks response variable?
You don't want to send a 500 error, since that implies an unexpected server-side error that is not caused by the user.
You'll want to read up on the rfc spec for status codes:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
4XX status codes are for client errors, which is where you'll want to be looking. In your case, you could use 401 if authentication failed, and 403 if that user is not allowed to view the resource.
How about returning HTTP401?
You can handle in in AJAX error handler and redirect the whole page to login screen, if it's your requirement.
$.ajax({
statusCode: {
401: function() {
alert("User not logged in");
}
}
});

Categories

Resources