Faking a 404, 500 and - http-status-codes

I am creating a simulation game (web service), and need to fake those error pages. As far as I know, and can see, there isn't a way to fake a 404, or 500 etc. Is this right? Are we able to do this programmatically?
I know I could just make a 404 page and redirect to it... But I'm trying to make it a little more realistic.

Returning a 404 or 500 status code to the browser (see your programming language's/framework's documentation for how) will send a real one instead of a fake one.

Copy whatever page your server sends for those particular errors (or just read the existing files if you've specified them explicitly) and write that out, then send the right status code along with it. For example, in PHP:
header("HTTP/1.1 500 Internal Server Error");

Here's how I'd do it using PHP:
<?php
header('HTTP/ 404'); //So that the browser thinks it's a legitimate 404 error.
#readfile($_SERVER['DOCUMENT_ROOT'] . '/404.html') or die('404 Not Found'); //Replace "/404.html" with your 404 page.
?>

Related

Rendering issue after AJAX call

I'm using Bottle microframework (but I doubt my issue comes from it)
First if I define a simple redirect from /test_redirect to /x it works. So Bottle redirect() on simple case works.
Now I have a page /buy that uses Stripe Checkout (custom form) pointing to my server /stripe_process
Basically Stripe Checkout verifies credit card transaction, creates a token and POST it to my /stripe_process.
/stripe_process does its stuff (calling Stripe to charge the card) then when transaction is success, i use instruct Bottle to:
redirect('/transaction_summary')
My webserver logs show that indeed /transaction_summary is called and server-side script is processed (I put flags in my script to check this), and its template is returned (browser 'Network' analysis gives a 303 then a 200 on /transaction_summary, I even get the correct response data: seems 100% normal), but on the browser page nothing happens (I still have my initial page /buy in url field, instead of having been redirected to /transaction_summary): browser received the /transaction_summary response, a preview is visible on Chrome devtools preview mode, but is not displaying it!
Also if in /stripe_process I change redirect() with a simple return template(), same issue: no data is processed by the browser.
Any clue ? This behaviour have been observed on 100% my tests:
- Firefox / Windows
- Chrome / iOS 9 (iPad)
- Chrome / linux
- Iceweasel / linux
- Chrome / Android
- Chrome / OSX
I suspect it has something to do with Stripe Checkout taking over something (since redirect() works perfectly in my simple test), but I can't figure the reason and how to solve this.
If from Chrome-devtools-network section I go to last action (ie /transaction_summary download) and open /transaction_summary in new tab, it renders perfectly.
So it's not a bottle problem, nor webserver. I suspect more on Stripe checkout modal/popup behaviour
$(window).on('popstate', function() { handler.close(); }); is present as stripe docs instruct but anyway stripe_handler is properly closed after token received (I checked with handler.closed callback...)
EDIT:
If I replace redirect() with straight return template(), same issue: html stuff is downloaded by the browser, avail on preview, but not rendered on main window.
EDIT2:
if I add on my page a href to /test_redirect redirecting to /x it works.
Note that this manual redirect work after Stripe checkout. The only difference with Stripe sequence here is user interaction ('click' on href) but as my redirect is same domain, browsers shouldn't block redirect anyway.
Problem was that AJAX call used to send Stripe token to /stripe_process was handling redirect response. That's why on network I had 200 answer from webserver but all html page data was going into the AJAX callback and rendered. Thanks to Thomas for raising my nose from this issue.
Solution is /stripe_process to return 1 in case of success (instead of server-side redireciton), then make the redirection from AJAX success callback.

Jmeter: 302 Moved Temporarily

I was trying to issue a https request through jmeter and observed am getting below response.
<html><head><title>302 Moved Temporarily</title></head>
<body bgcolor="#FFFFFF">
<p>This document you requested has moved temporarily.</p>
And it seems the actual url redirecting to different url which is getting the Response Code 200 which is OK. [The first urls response code is 302]
Also I have given an assertion for the page being loaded, but still that assertion fails [when I saw the response data in HTML format, observed that the respective page is not loaded]
Any help in resolving this issue would be a great help.
Looking at: http://jmeter.apache.org/usermanual/component_reference.html#Response_Assertion
If you chose "Main sample and sub samples" it will include the responses from the redirects. So for example if you're searching for "string" it will also include the response from the redirected page.

Should I check if file exists before responding via .sendFile()?

Say I have this route handler in my Express.js app:
app.get('/files/:name', function (req, res) {
res.sendfile('path/to/files/' + req.params.name + '.html');
});
This path is used via Ajax on my site. I wonder if I should guard against situations where a file with the requested name does not exist on the server, in which case the server returns a 404 response. I can work with this, i.e. detect the 404 in the browser and act accordingly (e.g. display a message to the visitor). However, I'm not sure if this is a good approach. Is it OK to use the 404 response here, or am I supposed to try to avoid 404 responses if possible. (E.g. I could if a file with the requested name exists on the server and only use .sendFile() if it does.)
I'm worried that performing a manual check would only slow things down as .sendFile() already has this check built-in (i.e. it's possible to avoid this check and instead detect 404 responses in the browser which is what I'm doing right now and it works fine).
I would stick with returning a 404 instead, as that's the 404's purpose.I'm not sure there really is any other common/practical alternative.
Good luck.

CodeIgniter returns 404 for all routes but works

I have strange problem with CodeIgniter and routing system and can't find solution for it, so: I have several routes such as
'forum/(:num)'
=> 'forum/category/$1',
'forum/(:num)/(page:any)'
=> 'forum/category/$1/$2',
and them works, but return 404 code in header.
I mean I don't get 404 page, correct HTML returns and page's content displays correctly for my forum's categories. But I'm getting 404 in header (Network tab in Firebug), so I can't work with POST data correctly.
If I request /forum/ - 200 Ok returns, but when I trying to get routed page, I get right page, but with 404 Not Found.
I'm using PHP5.4+Apache2 on Linux host, if it will help You to give me solution.
I've found solution! Maybe it will save someone's time.
Problem wasn't in CodeIgniter, I've found solution in activation mod_rewrite. Yes, that worked, but wan't activated in Apache.
Just try to do
sudo a2enmod rewrite
and restart apache service after
sudo service apache restart
And all routed pages will return 200 Ok
None of these worked, but I did this instead:
At the end of my controller I put this:
$this->output->set_status_header('200');
and actually though that worked, the problem turned out to be a controller name that conflicted with a real directory name...

NETWORK_ERROR: XMLHttpRequest Exception 101

I am getting this Error
NETWORK_ERROR: XMLHttpRequest Exception 101
when trying to get XML content from one site.
Here is my code:
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
if (xmlhttp==null) {
alert ("Your browser does not support XMLHTTP!");
return;
}
xmlhttp.onReadyStateChange=function() {
if(xmlhttp.readyState==4) {
var value =xmlhttp.responseXML;
alert(value);
}
}
xmlhttp.open("GET",url,false);
xmlhttp.send();
//alert(xmlhttp.responseXML);
}
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
Does any one have a solution?
If the url you provide is located externally to your server, and the server has not allowed you to send requests, you have permission problems. You cannot access data from another server with a XMLHttpRequest, without the server explicitly allowing you to do so.
Update: Realizing this is now visible as an answer on Google, I tried to find some documentation on this error. That was surprisingly hard.
This article though, has some background info and steps to resolve. Specifically, it mentions this error here:
As long as the server is configured to allow requests from your web application's origin, XMLHttpRequest will work. Otherwise, an INVALID_ACCESS_ERR exception is thrown
An interpretation of INVALID_ACCESS_ERR seems to be what we're looking at here.
To solve this, the server that receives the request, must be configured to allow the origin. This is described in more details at Mozilla.
The restriction that you cannot access data from another server with a XMLHttpRequest can apply even if the url just implies a remote server.
So:
url = "http://www.myserver.com/webpage.html"
may fail,
but:
url = "/webpage.html"
succeed - even if the request is being made from www.myserver.com
Request aborted because it was cached or previously requested? It seems the XMLHttpRequest Exception 101 error can be thrown for several reasons. I've found that it occurs when I send an XMLHttpRequest with the same URL more than one time. (Changing the URL by appending a cache defeating nonsense string to the end of the URL allows the request to be repeated. -- I wasn't intending to repeat the request, but events in the program caused it to happen and resulted in this exception).
Not returning the correct responseText or responseXML in the event of a repeated request is a bug (probably webKit).
When this exception occurred, I did get an onload event with readyState==4 and the request object state=0 and responseText=="" and responseXML==null. This was a cross domain request, which the server permits.
This was on an Android 2.3.5 system which uses webKit/533.1
Anyone have documentation on what the exception is supposed to mean?
Something like this happened with me when I returned incorrect XML (I put an attribute in the root node). In case this helps anyone.
xmlhttp.open("GET",url, true);
set the async part to true
I found a very nice article with 2 diferent solutions.
The first one implementing jQuery and JSONP, explaining how simple it is.
The second approach, it's redirecting trough a PHP call. Very simple and very nice.
http://mayten.com.ar/blog/42-ajax-cross-domain
Another modern method of solving this problem is Cross Origin Ressource Sharing.
HTML5 offers this feature. You can "wrap" your XMLhttp request in this CORS_request and
if the target browser supports this feature, you can use it and wont have no problems.
EDIT:
Additionaly i have to add that there are many reasons which can cause this Issue.
Not only a Cross Domain Restriction but also simply wrong Settings in your WEB.CONFIG of your Webservice.
Example IIS(.NET):
To enable HTTP access from external sources ( in my case a compiled Phonegap app with CORS request ) you have to add this to your WEB.CONFIG
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
Another scenario:
I got two webservices running... One on Port 80 and one on Port 90. This also gave me an XML HTTP Request Error. I even dont know why :). Nevertheless i think this can help many not well experienced readers.

Resources