简体   繁体   中英

Why aren't browsers displaying JSON data when fetched from Vue.js app

I'm trying to fetch data from my Python RESTfull API implemented in Flask and I got the following code set up.

tasks = {
  '1' : 'Learn',
  '2' : 'Build',
  '3' : 'Apply',
  '4' : 'Succeed'
}

@app.route('/alltasks')
def get_tasks():
   return jsonify(tasks)

The routing works perfectly fine when I enter the raw URL in the url bar as http://127.0.0.1:5000/alltasks and it displays the JSON data

{
  "1": "Learn", 
  "2": "Build", 
  "3": "Apply", 
  "4": "Succeed"
}

The issue is that I'm trying to access the data from my Vue.js application and but Chrome and the other browsers keeps giving me this error:

Cross-Origin Read Blocking (CORB) blocked cross-origin response http://127.0.0.1:5000/alltasks with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.

I confirmed that the API was doing what it should because I made a dummy route that just returned a message:

@app.route('/hi')
def say_hello():
    return 'Thank you for checking out my API'

and Vue accepted it just fine and it was displayed in the Network Diagnostic tools in Chrome. This is the code using Axios:

created: function() {
    this.loadAllTasks();
},
methods: {
loadAllTasks: function () {
    alert('At it');
    axios.get('http://127.0.0.1:5000/alltasks')
    .then(function(res, req){
        alert(res);
  });
}

The alert function isn't being executed because an error is being thrown.

Now I know that this question was asked and the most of the answers were to run Chrome and disable web security but do you really think every user is going to do that?

What is causing the error and what libraries can I use or code modification can I do to fix it?

What port is your vue.js web app running on? If it's running on a different port from your API (usually vue templates run on port 8080), the request will be blocked because it is viewed as a different origin (ie 127.0.0.1:8080 --> 127.0.0.1:5000). In order to resolve this, you can use the flask-cors library and define a list of origins that are allowed to access your api. I've never used it before, so I can't give specifics. The documentation is here (the Simple Usage section should give you what you need):

https://flask-cors.readthedocs.io/en/latest/

In particular, you should just need to add this to the top of your code (right after app is defined):

 cors = CORS(app, resources={r"/*": {"origins": "*"}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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