Tornado—添加请求头允许跨域请求访问

跨域请求访问

如果是前后端分离,那就肯定会遇到cros跨域请求难题,可以设置一个BaseHandler,然后继承即可。

class BaseHandler(tornado.web.RequestHandler):
    def __init__(self, *argc, **argkw):
        super(BaseHandler, self).__init__(*argc, **argkw)
        
    # 解决跨域问题
    def set_default_headers(self):
        self.set_header("Access-Control-Allow-Origin", "*")    # 这个地方可以写域名
        self.set_header("Access-Control-Allow-Headers", "x-requested-with")
        self.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
        self.set_header("Access-Control-Max-Age", 1000) 
        self.set_header("Content-type", "application/json")

    def get(self):
        self.write('request get')

    def post(self):
        self.write('request post')

    # vue一般需要访问options方法, 如果报错则很难继续,所以只要通过就行了,当然需要其他逻辑就自己控制。
    def options(self):
        # 返回方法1
        self.set_status(204)
        self.finish()
        # 返回方法2
        self.write('{"errorCode":"00","errorMessage","success"}')

继承BaseHandler类

class AdminTasks(BaseHandler):
    # 重写了BaseHandler父类的get方法
    def get(self):
        # 处理业务逻辑
        return self.write(json.dumps({"status": "success", "data": "请求成功"}))

    # 重写了BaseHandler父类的post方法
    def post(self):
        # 处理业务逻辑
        return self.write(json.dumps({"status": "success", "data": "请求成功"}))

主文件Main.py文件中

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [     
            (r"/tasks", AdminTasks),                      # 显示个人所有任务
        ]
        tornado.web.Application.__init__(self, handlers, **settings)
        
if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = Application()
    app.listen(options.port)
    print("visit at", "http://127.0.0.1:%s" % options.port)
    tornado.ioloop.IOLoop.instance().start()

这时候就可以通过:http://49.236.68.166:8008/tasks,访问后端了。

参考:https://www.cnblogs.com/renfanzi/p/6952871.html,https://www.cnblogs.com/zhangkui/p/11416575.html

附加内容:【Https异常】This request has been blocked; the content must be served over HTTPS

https://www.cnblogs.com/liqing1009/p/11290537.html,https://www.cnblogs.com/sslwork/p/6028940.html,https://www.cnblogs.com/756623607-zhang/p/11790283.html

你可能感兴趣的:(Tornado—添加请求头允许跨域请求访问)