Simple Javascript http request snippet but not work - perl

The code is modified from some tutorials as below:
xmlhttp=new XMLHttpRequest();
var url = "get_data.pl";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send(null);
I want get_data.pl script get executed and return the running result(print a string "test"), but I only got all lines of get_data.pl in xmlhttp.responseText. How should I do?
get_data.pl as below:
#!C:/Perl/bin/perl.exe
use strict;
use warnings;
&main;
sub main()
{
print "test";// I'd like the script being executed by Perl interpreter and return the string "test" .
}
Yes, Gar, you're right, thanks. I'm using Apache and I modified the httpd.conf's handler line(un-comment and add .pl) as you said. Now the issue seems resolved but I got another error:
POST http: //localhost/get_data.pl 403 (Forbidden)
I put the get_data.pl in the htdocs folder and the security option(OS Win7) has already being set to execute permission. So why being forbidden could you help me again?
Yes I've run the .pl from command line and without error.
Normally the .pl was put in cgi-bin folder which is a brother folder with "htdocs".
When I put the .pl in /cgi-bin and modified url to "../cgi-bin/get_data.pl", I got an error 500 which I guess the server didn't find the file. So any other configuration I missed in httpd.conf? Anyway, I moved it to htdocs folder to avoid the error 500...

Please ensure that you added a handler to .pl files in your http server.

Related

Trying to return a static file in web.py but getting "not found" error message

I have a web.py server hosted on pythonanywhere.com doing some handy things with python.
Now I'd like to just serve a straightforward html file from the same server i.e. just return the contents of a static html file to the client
The comments/answers below state that it should be possible, out of the box, to serve static files in the static directory, located in the same directory as the main python file which contains the following :
import web
urls = (
'/', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self):
return 'Hello, Joe'
if __name__ == "__main__":
app.run()
The server above works fine, when I go to http://myhost/ it displays "Hello , Joe".
The directory static exists and contains a file small.jpg but when I try the url http://myhost/static/small.jpg it gives me "not found"
Previous text of question up to Nov 9th 2022 is below :
original question title : Trying to return a html file in web.py but getting "No template named ....." error message
So I've looked at the web.py documentation on serving static files and templating and I think the following code should work :
import web
render = web.template.render('static/')
# have also tried render = web.template.render('/full/path/to/static/')
urls = (
'/getlatlongEIRCODE', 'getlatlongEIRCODE', #other stuff
'/getlatlongGOOGLE', 'getlatlongGOOGLE', #other stuff
'/getmonthlyPV', 'getmonthlyPV', #other stuff
'/Tomas', 'Tomas',
)
class Tomas:
def GET(self):
return render.Tomas()
I have created a folder static at the same level as my file above (which works fine for the other scripts) and i have created a file Tomas.html in the static folder containing
<h1>Help me</h1>
However I get an error message when I go to https://example.com/Tomas
<class 'AttributeError'> at /Tomas
No template named Tomas
P.S. From the static files page it seems to say I should just be able to put the Tomas.html file in a folder called "static" and then access is via https://example.com/static/Tomas.html but that is not working (it returns "not found")
You're using a relative path to your template directory without paying attention to the working directory. See https://help.pythonanywhere.com/pages/NoSuchFileOrDirectory/
You're working too hard. 'static' is built in.
As the documentation says, http://localhost/static/logo.png will return the file logo.png from the existing directory static, which is relative to your webserver root.
Do not use render() for this (not needed). Also, do not list your desired file ('/Tomas') in the urls list (not needed).
Anything under the static directory can be accessed with the url https://localhost/static/...
"static" is hardcoded in the web.py server, so you cannot (easily) change this to some other folder. The suggestion in the web.py documents is to have nginx or apache host your application and use an Alias there to go to web.py static. (I think you can also add StaticMiddleware to your web.py application, but you'd need to investigate that yourself -- look at web.application.run()
The case of the disappearing /static/ directory was related to the fact that I'm hosting on pythonanywhere.com
Even though the web.py documentation says that the /static/ folder is plugged in by default, that's not the case in pythonanywhere and you need to expressly make the link between the url http://yourhost/static/ and /path/to/static in the Web part of the dashboard.

How to resolve issue :: file_get_contents(http://localhost:8085/assets/data/test.txt): Failed to open stream: HTTP request failed

By using CodeIgniter 4 framework, I've developed RESTful api and there I need to access file (.json and .txt) to get content. But not able to access php inbuilt function file_get_contents().
For more details, pls check attached screenshot API_curl_file_get_content_error.PNG
And test.txt file is also accessible with same file path. For more details pls check screenshot Input-txt-file-content.png
NOTE : 1) test.txt file and respective directories have full permission.
2) Development environment :
<---->Apache/2.4.47 (Win64) OpenSSL/1.1.1k PHP/8.1.2
<---->Database client version: libmysql - mysqlnd 8.1.2
<---->PHP version: 8.1.2
<---->CodeIgniter 4
Product.php (index method)
<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
class Product extends ResourceController
{
use \CodeIgniter\API\ResponseTrait;
public function index()
{
helper("filesystem");
ini_set('max_execution_time', 300);
$data['msg'] = "Product Index wizard";
$data['status'] = 200;
$file_path = base_url() . '/assets/data/test.txt'; // Read JSON
$json = file_get_contents($file_path, true);
$json_data = json_decode($json, true);
return $this->respond($data);
}
}
Explanation:
Remember that "http://localhost:8085/" most likely points to the document root of the project, which is usually the /public path. So, unless the "assets" folder resides in the /public path, file_get_contents("http://localhost:8085/assets/data/test.txt"); will fail to find the requested server resource.
Solution:
Since your file resource (test.txt) is on the local filesystem,
Instead of:
file_get_contents("http://localhost:8085/assets/data/test.txt");
Use this:
constant ROOTPATH
The path to the project root directory. Just above APPPATH.
file_get_contents(ROOTPATH . "assets/data/test.txt");
Addendum:
I believe you also forgot to add the $json_data output to the returned $data variable in the Product::index resource controller method.

PHP Built-in Webserver and Relative Paths

TL;DR
Does PHP 5.4 built-in webserver have any bug or restriction about relative paths? Or does it need to be properly (and additionally) configured?
When I used to programming actively I had a system working under URI routing using these lines in a .htaccess file:
RewriteEngine On
RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php [L]
The FrontController received the Request, find the proper route from given URI in a SQLITE database and the Dispatcher call the the Action Controller.
It worked very nicely with Apache. Today, several months later I decided to run my Test Application with PHP 5.4 built-in webserver.
First thing I noticed, obviously, .htaccess don't work so I used code file instead:
<?php
if( preg_match( '/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"] ) ) {
return false;
}
include __DIR__ . '/index.php';
And started the webserver like this:
php.exe -c "php.ini" -S "localhost:8080" "path\to\testfolder\routing.php"
So far, so good. Everything my application need to bootstrap could be accomplished by modifying the include_path like this:
set_include_path(
'.' . PATH_SEPARATOR . realpath( '../common/next' )
);
Being next the core folder of all modules inside a folder for with everything common to all applications I have. And it doesn't need any further explanation for this purpose.
None of the AutoLoader techniques I've ever saw was able to autoload themselves, so the only class manually required is my Autoloader. But after running the Test Application I received an error because my AutoLoader could not be found. o.O
I always was very suspicious about realpath() so I decided to change it with the full and absolute path of this next directory and it worked. It shouldn't be needed to do as I did, but it worked.
My autoloader was loaded and successfully registered by spl_autoload_register(). For the reference, this is the autoloading function (only the Closure, of course):
function( $classname ) {
$classname = stream_resolve_include_path(
str_replace( '\\', DIRECTORY_SEPARATOR, $classname ) . '.php'
);
if( $classname !== FALSE ) {
include $classname;
}
};
However, resources located whithin index.php path, like the MVC classes, could not be found. So I did something else I also should not be doing and added the working directory to the include_path. And again, manually, without rely on realpath():
set_include_path(
'.' . PATH_SEPARATOR . 'path/to/common/next'
. PATH_SEPARATOR . 'path/to/htdocs/testfolder/'
);
And it worked again... Almost! >.<
The most of Applications I can create with this system works quite well with my Standard Router, based on SQLITE databases. And to make things even easier this Router looks for a predefined SQLITE file within the working directory.
Of course, I also provide a way to change this default entry just in case and because of this I check if this file exist and trigger an error if it doesn't.
And this is the specific error I'm seeing. The checking routine is like this:
if( ! file_exists( $this -> options -> dbPath ) ) {
throw RouterException::connectionFailure(
'Routes Database File %s doesn\'t exist in Data Directory',
array( $this -> options -> dbPath )
);
}
The dbPath entry, if not changed, uses a constant value Data/Routes.sqlite, relatively to working directory.
If, again, again, I set the absolute path manually, everything (really) works, the the Request flow reached the Action Controllers successfully.
What's going on?
This a bug in PHP's built-in web server that is still not fixed, as of PHP version 5.6.30.
In short, the web server does not redirect to www.foo.com/bar/ if www.foo./bar was requested and happens to be a directory. The client being server www.foo.com/bar, assumes it is a file (because of the missing slash at the end), so all subsequent relative links will be fetched relative to www.foo.com/instead of www.foo.com/bar/.
A bug ticket was opened back in 2013 but was mistakenly set to a status of "Not a Bug".
I'm experiencing a similar issue in 2017, so I left a comment on the bug ticket.
Edit : Just noticed that #jens-a-koch opened the ticket I linked to. I was not awar of his comment on the original question.

Python Screen Scraper works within Eclipse, but not from command line

I'm writing a simple screen scraping script using python 2.7 with Eclipse PyDev. When running or debugging from within Eclipse everything works fine. However, when I run my program from the command line the server always returns a Response 500 error code. I've tried running the script and the compiled versions from the command line but get the same result -- Response 500. I've also tried some arbitrary things like adding a delay, repeated attempts, etc. but I do not know what Eclipse is doing that is different than python ran the command line.
First, where's a good place to start digging if I encounter something like this again?
Second, any ideas on how to get this working from the command line?
Code snippet below for reference
from requests import Request, Session
content_type = 'application/x-www-form-urlencoded'
headers2 = {"User-Agent" : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
"Content-Type" : content_type,
"Referer" : url
}
url = loginPage
payload = {"email" : username, "password" : password}
req = Request ('POST', url, data=payload, headers=headers2)
prepped = req.prepare()
s = Session()
resp = s.send(prepped)
print resp # Response 200 (good) from both within Eclipse and from cmd
resp = s.get(targetPage)
print resp # Response 200 (good) from Eclipse, Response 500 (generic web error) from cmd
s.get (logOutPage)
s.close()
Got an answer from somebody. Thanks go to user Justinsaccount from reddit.
First, I was using batch files to save typing and not directly using the command line.
Secondly, when printing out the parameters from inside the program and then comparing the eclipse version versus the .bat version, the .bat version was short a few characters which was the give away.
One of the parameters was a url that had a space character: http://somewhere.com/some page.
In strict URL, this turns into: http://somewhere.com/some%20page
When run from the command line http://somewhere.com/some%20page
works just fine. However, in a batch file the % needed to be escaped so what I got was: http://somewhere.com/some0page
which is why the server through an error -- that page didn't exist. What I needed to do was escape the % character: http://somewhere.com/some%%20page. After that change things worked just fine.

javascript in perl code

i using javascript file (json2.js) in perl-cgi code with apache. but when i run it on browser, its unable to find the source and return following error;
'Failed to load resource: the server responded with a status of 404 (Not Found)'
my doumentroot path is : /srv/www/cgi-bin and scripts' path: /srv/www/cgi-bin/scripts
i doing this;
print "<script type='text/javascript' src='./scripts/json2.js'></script>"; # Line 1
print "<script type='text/javascript' language='JavaScript'>
function setDetails(o,json_arrRef,arrSize){
alert('hello='+arrSize+' || ref='+json_arrRef); // till here it works fine
var json_obj = JSON.parse(json_arrRef);
}
</script>";
if I edit Line 1 as
print "<script type='javascript' src='./scripts/json2.js'></script>";
it finds the source but gives following error when 'JSON.parse()' is called;
'Uncaught SyntaxError: Unexpected token ILLEGAL'
am I doing something wrong?
Don't put static files anywhere in or below /cgi-bin/ as servers are often configured to treat that path is a special way
Do get your type attributes correct, the content-type for JavaScript is text/javascript and not just javascript (technically speaking it should be application/javascript, but pretend it is text/javascript for the sake of browsers)
Don't compare JavaScript errors in the browser with Perl code and do look at what the webserver is outputting (i.e. the HTML and JavaScript source and/or which requests give 404 or other HTTP error codes)
Replace "./scripts/json2.js" with "/scripts/json2.js".