tornado django flask 跨域解决办法(cors)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.ioloop import tornado.web import json class 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 wraps from flask import make_response def 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_domain def domains(): pass
django
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.shortcuts import render from django.shortcuts import redirect # Create your views here. from app01 import models import datetime import json from django.shortcuts import HttpResponse from infrastructure.model.enterprise_news_data import Enterprise_news_Data from infrastructure.model.enterprise_news_data import Enterprise_News_Id_Info_Data from infrastructure.public import status_info from django.views.decorators.csrf import csrf_exempt @csrf_exempt def 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)的主要内容,如果未能解决你的问题,请参考以下文章
Django/Flask/Tornado三大web框架性能分析