Python:从BaseHTTPRequestHandler检索POST响应

时间:2015-11-12 13:59:10

标签: python post response basehttprequesthandler

我正在尝试使用BaseHTTPRequestHandler在Python请求后检索响应。为了简化问题,我有两个PHP文件。

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:'john@email.com'
                },
                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
    }
?>

使用 jquery_send.php ,我可以向 jquery_post.php 发送POST请求并成功检索请求。现在,我希望获得相同的结果将POST请求发送到Python BaseHTTPRequestHandler而不是 jquery_post.php 。我正在使用这个Python代码进行测试:

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()

我可以获取POST请求,但我无法在 jquery_send.php 中检索响应(“已接收!”)。我做错了什么?

编辑:

简而言之,我有一个使用BaseHTTPRequestHandler的小Python代码来获取POST请求并发送响应。

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()

我可以通过curl获得响应

curl --data "param1=value1&param2=value2" localhost:9080

但我无法从网页上使用ajax / jquery获取它(服务器正确接收POST请求,但网页不检索响应)。我该怎么办?

1 个答案:

答案 0 :(得分:1)

好的,问题是CORS标头,只要我从不同的端口(或类似的东西......)请求。添加

解决了这个问题
self.send_header('Access-Control-Allow-Credentials', 'true')
self.send_header('Access-Control-Allow-Origin', '*')

到我的回复标题。

相关问题