flask跨域请求三行代码搞定

flask跨域请求三行代码就可以搞定。但是请注意几点:

  第一:只能返回json格式数据,比如list、ndarray等都不可以

  第二:返回的对象必须是是字符串、元组、响应实例或WSGI可调用。

  python代码:

# coding:utf-8
from flask import Flask
import json
from flask_cors import *

app = Flask(__name__)
CORS(app, supports_credentials=True)

with open('./filmData.json','r') as f:
    data = f.read()

@app.route('/')
def index():            # 跨域请求数据的时候记住一定要是json类型的数据js才能转换
    return str(data)   #返回的对象必须是是字符串、元组、响应实例或WSGI可调用。

if __name__ == "__main__":
    app.run(debug=True)

  HTML、js代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript" src="js/jquery-3.3.1.min.js">
            
        </script>
    </head>
    <body>
        <div id="">
            八戒你瘦了!
        </div>
        
        <script type="text/javascript">
            $.ajax({
                type:'get',
                url:'http://127.0.0.1:5000/',
                async:true,
                complete:function(data){
                    console.log(data);
                    res = JSON.parse(data.responseText)
                    console.log(res)
                }
                
            })
            
        </script>
    </body>
</html>

猜你喜欢

转载自www.cnblogs.com/wuzaipei/p/9694379.html