如何将后端(python,flask)与前端(html,css,javascript)连接

时间:2019-04-06 12:41:47

标签: javascript python post flask get

信息:对于后端,我正在使用带烧瓶的python(目前它接受http get方法),对于前端,我正在使用html,css和javascript。

问题:我正在尝试发出http请求(第一次尝试POST,然后尝试GET),但是浏览器不允许我这样做:“从源地址访问'localhost:5000 / test'处的XMLHttpRequest “空”已被CORS策略阻止:跨协议请求仅支持以下协议方案:http,数据,chrome,chrome扩展名,https。”。

我还有什么选择? (我想要一些简单的选择,这只是一项作业)。

我尝试发出http POST和GET请求。 我读到我无法从浏览器发出http请求。 我读到我需要(例如)一个Apache服务器。 -太复杂了,我需要更简单的东西。 我已经尝试过:https://flask-cors.readthedocs.io/en/latest/

document.getElementById("btn").addEventListener('click', add);
function add()
{
    const url = "localhost:5000/test";
    const http = new XMLHttpRequest();
    http.open("GET", url);
    http.send();
    http.onreadystatechange=(e)=> {
        console.log(http.responseText)
    }
}
from flask import Flask
from flask_cors import CORS
from flask import request
from flask import jsonify
import json
import mysql.connector
import random
import string
import time

time.sleep(3)
app = Flask(__name__)

@app.route("/test")
def test():
    return "It's working"


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)

我希望在浏览器控制台中显示以下消息:“正在运行”,但出现错误: CORS策略已阻止从源“空”以“ localhost:5000 / test”访问XMLHttpRequest:仅协议方案支持跨源请求:http,数据,chrome,chrome扩展名,https。

LE:Flask服务器位于docker容器内。端口映射为“ 5000:5000”。

2 个答案:

答案 0 :(得分:1)

app = Flask(__name__)下添加以下行:

CORS(app)

签出flask-cors simple usage

答案 1 :(得分:0)

如果您使用的是同一台计算机,则无需使用secret_number = 6 guess_count = 0 guess_limit = 3 while guess_count < guess_limit: guess = int(input('Guess the secret number! ')) guess_count += 1 if guess == secret_number: print('...You Won!') if guess != secret_number: print('Nope. Try again!') break else: print('...Sorry, you failed.'

更新: 在使用Docker时,您可以使用flask-cors来处理CORS。

我发现您的JS代码中的AJAX调用不正确。 flask-cors不提供有关请求协议的信息。

我按照以下步骤操作,使用Docker成功运行Flask应用程序,并在Docker外部使用JS访问const url = "localhost:5000/test";端点。

  • 我更新了AJAX请求
  • 添加了/test以在Docker内部运行Flask应用程序
  • 构建并运行Dockerfile
  • 获取正在运行的Docker容器的IP地址。
  • 在Docker外部的JS代码中使用了AJAX调用中的IP地址。

文件夹结构:

Dockerfile

. ├── backend.py ├── Dockerfile ├── readme.md └── requirements.txt

requirements.txt

Flask==1.0.2 Flask-Cors==3.0.7

Dockerfile

构建Docker文件:

FROM python:3
ENV PYTHONBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/
CMD ["python", "backend.py" ]

运行Docker:

docker build -t flask-docker .

获取Docker容器ID:

docker run -p 5000:5000 flask-docker

* Serving Flask app "backend" (lazy loading)
* Environment: production
  WARNING: Do not use the development server in a production environment.
  Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

获取Docker容器IP地址:

docker ps

CONTAINER ID        IMAGE                   COMMAND                CREATED             STATUS              PORTS                    NAMES
69cb7d5d243a        flask-docker            "python backend.py"    15 minutes ago      Up 15 minutes       0.0.0.0:5000->5000/tcp

在HTML文件的AJAX请求中使用此IP地址:

docker inspect --format '{{ .NetworkSettings.IPAddress }}' 69cb7d5d243a  

172.17.0.2

<html> <head> <title>Frontend</title> </head> <body> <div id="data"></div> <button type="button" id="btn">Grab data</button> <script type="text/javascript"> document.getElementById("btn").addEventListener('click', add); function add() { const api_url = "http://172.17.0.2:5000/test"; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("data").append(this.responseText); } }; xhttp.open("GET", api_url, true); xhttp.send(); } </script> </body> </html>

backend.py

输出:

{{3}}