Reputation: 197
I'm trying to retrieve the response after a POST request with Python using a BaseHTTPRequestHandler. To simplify the problem, I have two PHP files.
jquery_send.php
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function sendPOST() {
url1 = "jquery_post.php";
url2 = "http://localhost:9080";
$.post(url1,
{
name:'John',
email:'[email protected]'
},
function(response,status){ // Required Callback Function
alert("*----Received Data----*\n\nResponse : " + response + "\n\nStatus : " + status);
});
};
</script>
</head>
<body>
<button id="btn" onclick="sendPOST()">Send Data</button>
</body>
</html>
jquery_post.php
<?php
if($_POST["name"])
{
$name = $_POST["name"];
$email = $_POST["email"];
echo "Name: ". $name . ", email: ". $email; // Success Message
}
?>
With jquery_send.php, I can send a POST request to jquery_post.php and retrieve the request successfully. Now, I want to get the same result sending the POST request to a Python BaseHTTPRequestHandler instead jquery_post.php. I'm using this Python code for testing:
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class RequestHandler(BaseHTTPRequestHandler):
def do_POST(self):
print("\n----- Request Start ----->\n")
content_length = self.headers.getheaders('content-length')
length = int(content_length[0]) if content_length else 0
print(self.rfile.read(length))
print("<----- Request End -----\n")
self.wfile.write("Received!")
self.send_response(200)
port = 9080
print('Listening on localhost:%s' % port)
server = HTTPServer(('', port), RequestHandler)
server.serve_forever()
I can get the POST request, but I can't retrieve the response ("Received!") in jquery_send.php. What am I doing wrong?
EDIT:
In short, I have this little Python code using a BaseHTTPRequestHandler to get a POST request and send a response.
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class RequestHandler(BaseHTTPRequestHandler):
def do_POST(self):
print(self.rfile.read(int(self.headers['Content-Length'])).decode("UTF-8"))
content = "IT WORKS!"
self.send_response(200)
self.send_header("Content-Length", len(content))
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write(content)
print "Listening on localhost:9080"
server = HTTPServer(('localhost', 9080), RequestHandler)
server.serve_forever()
I can get the response with curl
curl --data "param1=value1¶m2=value2" localhost:9080
but I can't get it using ajax/jquery from a webpage (the server receives the POST request correcty, but the webpage doesn't retrieve the response). How can I do it?
Upvotes: 0
Views: 3085
Reputation: 197
Ok, the problem was the CORS headers, as long as I was requesting from a different port (or something like that...). The problem is solved adding
self.send_header('Access-Control-Allow-Credentials', 'true')
self.send_header('Access-Control-Allow-Origin', '*')
to my response headers.
Upvotes: 4