Python Web服务器未响应CORS请求

时间:2019-05-07 17:15:12

标签: python python-3.x server cors

我认为CORS标头均已正确设置。服务器启动,但尝试使用Postman或我的React Web应用程序发送POST请求,服务器不响应,也不打印POST参数。如果我取消了Postman的POST请求,它将打印参数和请求详细信息。

我花了几个小时试图在Python 3中找到一个可行的示例来构建CORS API服务器(测试网络应用程序时Google Chrome似乎需要CORS),但是我没有这么做不成功。

from http.server import HTTPServer, SimpleHTTPRequestHandler
import json

class CORSRequestHandler (SimpleHTTPRequestHandler):

    def do_OPTIONS(self):
        self.send_response(200, "ok")
        self.send_header('Access-Control-Allow-Origin',
                         self.headers['origin'])
        self.send_header("Access-Control-Allow-Headers",
                         "Origin, X-Requested-With, Content-Type, Accept")
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.end_headers()

    def do_POST(self):

        parameters = json.load(self.rfile)
        print(parameters)

        body = bytes(json.dumps({'trial': 'blablalbla'}), 'utf-8')

        self.send_response(200)
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Headers",
                         "Origin, X-Requested-With, Content-Type, Accept")
        self.send_header('Content-Type', 'application/json'),
        self.end_headers()

        self.wfile.write(body)


if __name__ == '__main__':
    httpd = HTTPServer(('localhost', 9000), CORSRequestHandler)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass

我从Postman和React应用程序都以JSON形式发送请求正文。我想念什么?

0 个答案:

没有答案