首页 > 代码库 > tornado django flask 跨域解决办法(cors)

tornado django flask 跨域解决办法(cors)

XMLHttpRequest cannot load http://www.baidu.com. No ‘Access-Control-Allow-Origin‘ header is present on the requested resource. Origin ‘http://10.16.16.25:9988‘ is therefore not allowed access.

 tornado

 这个就是典型的cors,允许后端允许跨域的方法。第二种方法,反向代理还在实践中

#!/usr/bin/env python# -*- coding:utf-8 -*-import tornado.ioloopimport tornado.webimport jsonclass IndexHandler(tornado.web.RequestHandler):    def get(self):        self.render(index.html)class AaaHandler(tornado.web.RequestHandler):    def post(self, *args, **kwargs):        ret = self.get_argument("k1")        print(ret)        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.write(json.dumps("aa"))settings = {    template_path: views,    static_path: static,    static_url_prefix: /static/,}application = tornado.web.Application([    (r"/index", IndexHandler),    (r"/aaa", AaaHandler),], **settings)if __name__ == "__main__":    application.listen(8888)    tornado.ioloop.IOLoop.instance().start()

 Flask

from functools import wrapsfrom flask import make_responsedef allow_cross_domain(fun):    @wraps(fun)    def wrapper_fun(*args, **kwargs):        rst = make_response(fun(*args, **kwargs))        rst.headers[Access-Control-Allow-Origin] = *        rst.headers[Access-Control-Allow-Methods] = PUT,GET,POST,DELETE        allow_headers = "Referer,Accept,Origin,User-Agent"        rst.headers[Access-Control-Allow-Headers] = allow_headers        return rst    return wrapper_fun@app.route(/hosts/)@allow_cross_domaindef domains():    pass

django

#!/usr/bin/env python# -*- coding: utf-8 -*-from django.shortcuts import renderfrom django.shortcuts import redirect# Create your views here.from app01 import modelsimport datetimeimport jsonfrom django.shortcuts import HttpResponsefrom infrastructure.model.enterprise_news_data import Enterprise_news_Datafrom infrastructure.model.enterprise_news_data import Enterprise_News_Id_Info_Datafrom infrastructure.public import status_infofrom django.views.decorators.csrf import csrf_exempt@csrf_exemptdef enterprise_news(request):    """    企业信息    :param request:    :return:    """    if request.method == POST:        ret = Enterprise_news_Data().select_enterprise_news()        return_status = status_info.api_status()        return_status.status["status"] = 0        return_status.status["message"] = "成功"        return_status.status["return_info"] = ret        print(return_status.status)        # return HttpResponse(json.dumps(ret))        response = HttpResponse(json.dumps(return_status.status))        response["Access-Control-Allow-Origin"] = "*"        return response    else:        return HttpResponse()

 

tornado django flask 跨域解决办法(cors)