首页 > 代码库 > 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)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。