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()
作者:沐禹辰
出处:http://www.cnblogs.com/renfanzi/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
出处:http://www.cnblogs.com/renfanzi/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。