What is the correct status code when a POST request successfully logs out a user and redirects to the home page? - node.js

Environment: Node.js, Express
Question: What is the correct status code for a situation in which a POST request successfully logs out a user and redirects the client to the home page?
Background: I use a POST request to log out clients. At the end of a successful log out I use, return res.redirect('/') to forward the user to the home page.
When I checked the headers in Dev Tools I saw that Express was by default sending a 302 status code. However in my situation I'm not sure if that's right because resources have not been moved temporarily or permanently. When an internal redirect happens due to the normal operation of a server what is the correct status code to send?
Request URL: https://www.example.com/logout
Request Method: POST
Status Code: 302
Remote Address: 1.1.1.1:443
Referrer Policy: strict-origin
Below in the response header it shows
location: /

It's 303 - See other. The "resource" has not been moved because there is no resource to speak of - you're displaying a related page, which is, however, not the representation of the hypothetical "logout resource".

Related

Browser not showing Internal Server Error HTML Page with status 500

I've two components in my application. A frontend which is built on Angular and backend built using express. I'm using the Nest.js framework in the backend.
I have an http-exception.filter.ts file which takes care of any thrown exception. So far, I've been handling Internal Server Error in the application this way.
if(exception.getStatus() === 500) {
response
.status(500)
.json({
status: '500',
code: 'INTERNAL_SERVER_ERROR',
message: 'Internal Server Error'
});
}
But, now an HTML page has been designed showing Internal Server Error message. All I need to do to render that page is to hit the URL /ui/internal-server-error. So, I tried to that using the code below.
response
.status(500)
.redirect('/ui/internal-server-error');
The page loads when a case of internal server error occurs, but the problem is I'm not getting 500 status when I'm reading the network logs in the browser. Instead, I'm getting 304 Not modified status.
Could anyone please point me in the right direction? I want to show the error page along with status code 500 and the UI page needs to come from Frontend only as I've no access over it.
When redirect is called, it sets the status, so the 500 is replaced.
From the express docs (relevant as NestJS uses Express by default):
Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code . If not specified, status defaults to “302 “Found”.
res.redirect('/foo/bar')
res.redirect('http://example.com')
res.redirect(301, 'http://example.com')
res.redirect('../login')
Add the desired status as an argument to redirect.

How can I return server side error to the client's HTML page in Express/node js?

I am creating an web app I which the user requests to create an account. The request from client's page will reach the server and query the database. Now what is the proper way of displaying User already exists error in my registeration page. In short, how can I send server side errors to my clients in Node JS?
There are some options to get what you need. The approach that I would not follow will be using the http protocol and sending a 500 response for example.
One good approach would be creating a status and a message fields in your response.
You could use code 200 for the sucessful requests and a different code for the rest. You could have a dedicated code to inform the api user that the backend coud not insert the data.
Example response:
{
code: 789
message: "User could not be inserted"
...
}

204 error code then 500 error code responses

So I have an application which needs to send data to the API which is created by our team leader using NodeJS with Express.js.
On my end I have laravel application which using VueJS for the UI. Inside the Vue JS component. I am using axios to request to the API.
axios.post('https://clearkey-api.mybluemix.net/sendcampaign', request)
.then(function(response) {
//console.log(response);
})
However, it returns 204 which means according to this https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
204 No Content
The server has fulfilled the request but does not need to return an
entity-body, and might want to return updated metainformation. The
response MAY include new or updated metainformation in the form of
entity-headers, which if present SHOULD be associated with the
requested variant.
If the client is a user agent, it SHOULD NOT change its document view
from that which caused the request to be sent. This response is
primarily intended to allow input for actions to take place without
causing a change to the user agent's active document view, although
any new or updated metainformation SHOULD be applied to the document
currently in the user agent's active view.
The 204 response MUST NOT include a message-body, and thus is always
terminated by the first empty line after the header fields.
Then next it returns 500 Internal Server Error. So in my opinion it returns this error because there is no content to be returned from the server?
Can you tell me other possible problems why it return that response?
Check if the "HTTP method" of the 204 is OPTIONS and if the method of the 500 is POST.
If both are like that, then you are seeing first a CORS pre-flight request (the OPTIONS that returns 204) and then the actual request (the POST that returns 500).
The CORS pre-flight request is a special HTTP message your browser sends to the server when the webpage and the backend are hosted at different addresses. For example, if your website is hosted at http://localhost but the backend you are trying to access is hosted at https://clearkey-api.mybluemix.net.
The reason of the 204 just means your backend endpoint is correctly setup to handle requests for /sendcampaign (you can ignore it). The reason of the 500 is because of some exception in the implementation of the function that handles that endpoint.

404 status code returned by silex is not redirected by .htaccess

my .htaccess works fine when I type manually a wrong url it redirects to my custom 404 page. Here is my .htaccess (this the hole content (no other redirects)):
RewriteEngine on
ErrorDocument 404 http://codeexample.local/404.shtml
Now in my Silex based application I return a 404 status code if the client tries to edit a non existent client. Even though the status code is indeed 404 as i can see with curl -v. But for some reason it is not redirected to 404 error page.
Here is how I access the url:
http://codeexample.local/index.php/2/edit
Here is my index.php edit route section:
$app->match('/{id}/edit', function (Request $request, $id) use ($app) {
try {
$clientController = new ClientController($request, $id);
return $clientController->editAction($app);
}
catch(\Exception $e){
return $e->getMessage();
}
})
->assert('id', '\d+')
->method('GET|POST');
in my editAction method I am checking if the client exists in the database otherwhise I am returning a response like this:
$response = new Response(
'',
Response::HTTP_NOT_FOUND,
array('content-type' => 'text/html')
);
$response->prepare($request);
$response->send();
return $response;
Thanks
you should redirect to the error page.
$app->redirect( '/404.shtml' );
In your code you are creating a new Response with a statuscode. This is too late for the apacheserver to react.
And other idea is to call the function which creates the errorpage, but i would say don't do that to keep the code clean.
Your expectations are a bit off here, possibly. The web server will handle requests for addresses it has no knowledge of with a 404 response, and you can also provide it with some HTML to send along with the 404 response. But it's the 404 response that is really the important bit.
Telling the web server that 404.shtml is the mark-up to send back to the browser is not like a redirect to that page, it simply uses the contents of that file for the HTML to send back with the 404 response.
Silex knows nothing about that, as the web server's 404-handling is long since fallen out of the picture by the time Silex gets anywhere near the request. When there's a 404 condition at the Silex end of things you need to do two things: return a 404 code in the response (you're doing that now), and you can optionally send some content back too (like the markup in that 404.shtml file). If you want to have the same 404 mark-up as the 404.shtml that the web server uses... read that file and return it as the content with your 404 response.
You could try to go a different route and rejig your web server 404 to return the result of a Silex-routed URL, and then use that same route internally for the content of 404s from Silex too, but I think it's the wrong approach for the web server to be bugging PHP/Silex for a response to a request which has already been identified as invalid.
What you really really do not want to do is redirect from Silex to a doc containing mark-up for a 404. What that will do is tell the user agent that the URL it tried was incorrect, and it should try another one (as provided by the redirect header), which will then return a 404 message to the human in the mark-up, but will be returning 200-OK to the user agent. So in effect when a user agent browses to /someBadPage.html you'd be telling them the correct document for that URL is /404.html. Not that /someBadPage.html does not exist.

enyo is giving me a "not allowed by Access-Control-Allow-Origin".and will not load content from nodejs server

I made the simple hello world NODEJS Server.
I have a enyo web service running in chrome that is trying to access the NODEJS server at http://localhost:3000
When is calls the onSuccess method, no data is loaded and the consule shows the following error
XMLHttpRequest cannot load http://localhost:3000/. Origin http://localhost:81 is not allowed by Access-Control-Allow-Origin.
I tested the nodejs server in the browser, it worked fine.
I tried to set the --disable-web-security, flag in chrome, it did not work.
Does anybody know how to fix this problem? If NOD.js is running on another server, would it work? This security is so confusing.
Ted
For security reasons, browsers limit the requests that a script may make via XMLHttpRequest.
Your requests will only succeed under the following 2 cases:
The origin of the URI that your script loads is the same as the origin of the page on which the script is executing (localhost:81 and localhost:3000 are the same host but different origins);
or, if your browser supports it, the server of the page being requested includes an Access-Control-Allow-Origin header which explicitly authorizes pages served from the origin in question (or pages served from all origins) to make XMLHttpRequests to it.
Try adding the Accesss-Control-Allow-Origin header to whatever is generating the response in your node code, adding a header in some code that looks like this:
response.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin' : 'http://localhost:81'
//allow anything by replacing the above with
//'Access-Control-Allow-Origin' : '*'
});

Resources