zoukankan      html  css  js  c++  java
  • Flask解决跨域

    Flask解决跨域

    问题:
    网页上(client)有一个ajax请求,Flask sever是直接返回 jsonify。

    然后ajax就报错:No 'Access-Control-Allow-Origin' header is present on the requested 

    原因:
    ajax跨域访问是一个老问题了,解决方法很多,比较常用的是JSONP方法,JSONP方法是一种非官方方法,而且这种方法只支持GET方式,不如POST方式安全。

    即使使用jquery的jsonp方法,type设为POST,也会自动变为GET。

    官方问题说明:

    “script”: Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, “_=[TIMESTAMP]“, to the URL unless the cache option is set to true.Note: This will turn POSTs into GETs for remote-domain requests.

    如果跨域使用POST方式,可以使用创建一个隐藏的iframe来实现,与ajax上传图片原理一样,但这样会比较麻烦。

    因此,通过设置Access-Control-Allow-Origin来实现跨域访问比较简单。

    例如:客户端的域名是www.client.com,而请求的域名是www.server.com

    如果直接使用ajax访问,会有以下错误

    XMLHttpRequest cannot load http://www.server.com/xxx. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://www.client.com' is therefore not allowed access.

    解决

    在被请求的Response header中加入header,

    一般是在Flask views.py

    方法一:

    @app.after_request
    def cors(environ):
        environ.headers['Access-Control-Allow-Origin']='*'
        environ.headers['Access-Control-Allow-Method']='*'
        environ.headers['Access-Control-Allow-Headers']='x-requested-with,content-type'
        return environ

    方法二:

    from flask import Flask, request, jsonify, make_response
    
    @app.route('/login', methods=['POST', 'OPTIONS'])
    def login():
        username = request.form.get('username')
        pwd = request.form.get('pwd')
        
        if username == 'h' and pwd == '1':
            res = make_response(jsonify({'code': 0,'data': {'username': username, 'nickname': 'DSB'}}))
            res.headers['Access-Control-Allow-Origin'] = '*'
            res.headers['Access-Control-Allow-Method'] = '*'
            res.headers['Access-Control-Allow-Headers'] = '*'
    
            return res

    方法三:没试过

    在Flask开发RESTful后端时,前端请求会遇到跨域的问题。下面是解决方法。Python版本:3.5.1

    下载flask_cors包
    pip install flask-cors
    
    使用flask_cors的CORS,代码示例
    
    from flask_cors import *
    
    app = Flask(__name__)
    CORS(app, supports_credentials=True)



  • 相关阅读:
    Git Cannot rebase: You have unstaged changes.
    importError: DLL load failed when import matplotlib.pyplot as plt
    install tushare in python 3.6
    pd.qcut, pd.cut, df.groupby()等在分组和聚合方面的应用
    从池子里的beta看秋香, 个性迥异
    个股和股票池的beta系数的估算
    检验两个随机序列的beta系数
    spyder里的"查找文件里的特定字符串"非常方便
    地图上道路编号中的G S X Y
    场内的代码表, 感觉水很深
  • 原文地址:https://www.cnblogs.com/hanbowen/p/9899088.html
Copyright © 2011-2022 走看看