简体   繁体   English

RESTful API-Flask-> jQuery-错误

[英]RESTful API - Flask -> Jquery - Error

I am studying about RESTful APIs and I decided to create a small server and a consumer to test. 我正在研究RESTful API,因此决定创建一个小型服务器和一个使用者进行测试。

I'm using Flask as a server and an example I took on the internet to consume this API. 我使用Flask作为服务器,并在互联网上使用了一个示例来使用此API。 But I'm having some problems. 但是我有一些问题。

The error message on the console says this: XMLHttpRequest cannot load http://127.0.0.1:5000/api/tasks. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 控制台上的错误消息表明: XMLHttpRequest cannot load http://127.0.0.1:5000/api/tasks. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. XMLHttpRequest cannot load http://127.0.0.1:5000/api/tasks. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

But I do not know what it can be. 但是我不知道会是什么。

Flask server code: 烧瓶服务器代码:

from flask import Flask, jsonify

app = Flask(__name__)

tasks = [
    {
        'id':1,
        'title': u'Estudo',
        'description': u'Sistemas Distribuidos',
        'done':True
    },
    {
        'id':2,
        'title': u'Monitoria',
        'description': u'Programacao e Algoritmos',
        'done': False
    }
]


@app.route('/')
def index():
    return "URL PARA O ACESSO DA API: '/api/tasks'"

@app.route('/api/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': tasks})

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

Example code using Jquery: 使用Jquery的示例代码:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
  <meta charset="utf-8">
  <title>Mashape Query</title>
  <script>
    function doIt() { 
 var output = $.ajax({
    url: 'http://127.0.0.1:5000/api/tasks', // The URL to the API. You can get this by clicking on "Show CURL example" from an API profile
    type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc
    data: {}, // Additional parameters here
    dataType: 'json',
    success: function(data) {
        //console.log(data);
        alert(data);
        document.getElementById("output").innerHTML = data.source; 
        },
    error: function(err) { alert(err.getText); }
});


}

</script>
</head>
<body>

  <button onclick="doIt()">Run the request</button>
  <div id="output">The API request is:</div>

</body>
</html>

Most likely the easiest is to install https://flask-cors.readthedocs.io/en/latest/ . 最可能最简单的方法是安装https://flask-cors.readthedocs.io/en/latest/

From their Simple Usage guide: 从他们的“ Simple Usage指南中:

from flask import Flask
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
    return "Hello, cross-origin-world!"

If you don't want to install another package, you can try to use the solution from here https://stackoverflow.com/a/33091782/2525104 by Salvador Dali. 如果您不想安装其他软件包,则可以尝试从此处下载Salvador Dali的解决方案https://stackoverflow.com/a/33091782/2525104

@app.route('your route', methods=['GET'])
def yourMethod(params):
    response = flask.jsonify({'some': 'data'})
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM