烧瓶不向JS发送数据

问题描述

可以看到,我正在尝试将烧瓶中的数据发送到js。但是,我一直遇到404 Not found。我似乎也不知道我要求的专业py和js开发人员。我还在"<url>:<flask_port>/Send"

中尝试过"http://127.0.0.1:5000/Send"app.route

烧瓶

@app.route('/Send',methods=['POST','GET'])
def SendData():
    Data = {'Hour':"30","Min":"2"}
    JSONed = json.dumps(Data)
    return render_template('index.html')

if __name__ == '__main__':
    app.run()

JS

fetch('/Send') 
.then(function (response) { 
    return response.text();
}).then(function (text) {
    console.log(text); 
});    

HTML

<body>
    <script src="static/app.js"></script>
</body>

树:

C:.
│   app.py
│
├───.vscode
│       settings.json
│
├───static
│       app.js
│
├───templates
│       index.html
│
└───__pycache__
        app.cpython-38.pyc

日志:

127.0.0.1 - - [16/Oct/2020 01:06:16] "GET /Send HTTP/1.1" 200 -
127.0.0.1 - - [16/Oct/2020 01:06:16] "GET /static/app.js HTTP/1.1" 200 -
127.0.0.1 - - [16/Oct/2020 01:06:16] "GET /%3Curl%3E:%3Cflask_port%3E/Send HTTP/1.1" 404 -

错误

Failed to load resource: the server responded with a status of 404 (NOT FOUND)

解决方法

在您的端点中,我看不到您如何将数据发送到前端

@app.route('/Send',methods=['POST','GET'])
def SendData():
    Data = {'Hour':"30","Min":"2"}
    JSONed = json.dumps(Data)
    return render_template('index.html')

if __name__ == '__main__':
    app.run()

更改为此:

from flask import jsonify


@app.route('/Send',"Min":"2"}
    return jsonify(Data)

if __name__ == '__main__':
    app.run()

由于json示例,我怀疑您正在使用json对象

fetch('/Send') 
.then(function (response) { 
    return response.text();
}).then(function (text) {
    console.log(text); 
});    

javascript示例中,您似乎正在从另一个端点渲染此HTML,但是您想通过javascript从另一个端点收集数据。

我会这样:

@app.route('/Send','GET'])
def send_data():
    data = {'Hour':"30","Min":"2"}
    return render_template('index.html',data=data)

if __name__ == '__main__':
    app.run()

然后我将使用HTML模板机制在jinja2中渲染数据,如下所示:

<body>
    <p> {{ data }} </p>
</body>