无法从JavaScript连接到Flask REST API

时间:2020-05-16 19:33:02

标签: javascript api rest flask fetch-api

我尝试使用Flask并从JavaScript访问它来制作一个远程REST API,但是它不起作用,它无法访问该API,我也不知道为什么,但是当我在URL中输入URL时浏览器我可以看到结果。 这是我的代码:

在目录中找到的

来自 init .py的代码:

from flask import Flask
from flask_restful import Resource, Api
app = Flask(name)

api = Api(app)
@app.route("/")

def get_list():
    return ['some', 'strings']

class SomeClass(Resource):
    def get(self):
        value = get_list()
        return {'key': value}, 200

api.add_resource(SomeClass, '/users')

来自run.py的代码:

from directory import app

app.run(host='0.0.0.0', port=5050, debug=True)

这是JavaScript中的代码:

<script>
    function plzwork() {

        var requestOptions = {
            method: 'GET',
            redirect: 'follow',
            body: '2',
            cache: 'no-cache'
        };

        fetch("<remote_public_IP>:<port>/", requestOptions)
            .then(response => response.json())
            .then(data => console.log(data));
        //  .then(result => console.log(result))
        //  .catch(error => console.log('error', error));

    }</script>

2 个答案:

答案 0 :(得分:1)

首先,我不确定您的后端是否真正起作用,但这是经过一些更改的代码:

安装flask-cors模块:

pip install -U flask-cors

烧瓶-> init.py

from flask import Flask
from flask_restful import Resource, Api
from flask_cors import CORS # + added

app = Flask(__name__)
CORS(app) # + added

api = Api(app)
@app.route("/") # you don't need this if you use Flask_restful
def get_list():
    return ['some', 'strings']

class SomeClass(Resource):
    def get(self):
        value = get_list()
        return {'key': value}, 200

api.add_resource(SomeClass, '/users')

JavaScript-> body: '2'已被注释掉:

<script>
    function plzwork() {

        var requestOptions = {
            method: 'GET',
            redirect: 'follow',
            // body: '2', 
            cache: 'no-cache'
        };
        fetch("http://127.0.0.1:5000/users", requestOptions)
            .then(response => response.json())
            .then(data => console.log(data));
        //  .then(result => console.log(result))
        //  .catch(error => console.log('error', error));

    }
</script>

您的HTML(请注意,我将href标记更改为可用于测试):

<li class="nav-item" onclick="plzwork()" role="presentation"><a class="nav-link" href="http://127.0.0.1:5000/users">
<i class="fa fa-tasks"></i><span>All Tasks<br></span></a></li>

结合HTML + JS以便于实现:

<html lang="en">
    <head>
        <title></title>
    </head>
<body>
<li class="nav-item" onclick="plzwork()" role="presentation"><a class="nav-link" href="http://127.0.0.1:5000/users">
<i class="fa fa-tasks"></i><span>All Tasks<br></span></a></li>


<script>
    function plzwork() {

        var requestOptions = {
            method: 'GET',
            redirect: 'follow',
            cache: 'no-cache'
        };
        fetch("http://127.0.0.1:5000/users", requestOptions)
            .then(response => response.json())
            .then(data => console.log(data));
        //  .then(result => console.log(result))
        //  .catch(error => console.log('error', error));

    }
</script>

    </body>
</html>

答案 1 :(得分:-1)

请检查您的浏览器console.error吗?我想问题是CORS,请从您的flask应用程序启用CORS。您可以获得更多here