9

I'm trying to display some json data from a flask server to my html page but I have a TypeError: NetworkError when attempting to fetch resource. with a Promise { <state>: "rejected" }.

server.py

from flask import Flask, request, jsonify

app = Flask(__name__)


@app.route('/hello', methods=['GET'])
def hello():
    jsonResp = {'jack': 4098, 'sape': 4139}
    print(jsonify(jsonResp))
    return jsonify(jsonResp)

if __name__ == '__main__':
    app.run(host='localhost', port=8989)

script.js

function getHello() {
    const url = 'http://localhost:8989/hello'
    const response = fetch(url)
    console.log(response);
    document.getElementById("demo").innerHTML = response;
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <button onclick="getHello()">click</button>
    <label id="demo"></label>

    <script src="script.js"></script>
</body>
</html>

I also have a [object Promise] in the label section when I click on the button.

I did the simplest code possible but it doesn't work.

2
  • Try this stackoverflow.com/questions/57857647/… fetch is a new api which might have issues. The code i use is definitly working and should return at least something. Commented Sep 11, 2019 at 14:31
  • I'm definitively doing something wrong here with your code I still have an network error NetworkError: A network error occurred. but no more promise things. I've also test with axios had the same issue Commented Sep 11, 2019 at 14:43

3 Answers 3

14

Thanks all for your good answers :) Here is my final code :

server.py

from flask import Flask, request, jsonify, after_this_request

app = Flask(__name__)


@app.route('/hello', methods=['GET'])
def hello():
    @after_this_request
    def add_header(response):
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response

    jsonResp = {'jack': 4098, 'sape': 4139}
    print(jsonResp)
    return jsonify(jsonResp)

if __name__ == '__main__':
    app.run(host='localhost', port=8989)

script.js

function getHello() {
    const url = 'http://localhost:8989/hello'
    fetch(url)
    .then(response => response.json())  
    .then(json => {
        console.log(json);
        document.getElementById("demo").innerHTML = JSON.stringify(json)
    })
}
Sign up to request clarification or add additional context in comments.

1 Comment

It took me a while to figure out that index.html is served elsewhere (for example second shell running flask), but after that it worked great.
7

This could be caused by Same-Origin Policy. Browser does not allow making calls to different origin unless server sets special HTTP header. If you are opening this html file from your browser, the origin of server which is localhost does not match with the origin in your browser which is probably a file path. You can make it work by adding Access-Control-Allow-Origin header to the response as follows:

from flask import after_this_request

@app.route('/hello', methods=['GET'])
def hello():
    @after_this_request
    def add_header(response):
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response

    jsonResp = {'jack': 4098, 'sape': 4139}
    print(jsonify(jsonResp))
    return jsonify(jsonResp)

Now there is no network error but your promise is pending so you need to add then for it.

Alternatively you can serve index.html file by your Flask server so that origins match.

You can read more about CORS and SOP here:

https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Comments

4

fetch() returns a promise, if you want to use .json() it returns another promise. You cound use .then() to get the json response.

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())  
  .then(json => console.log(json))
  

But you have another error probably related to cors in your flask server, try this before the return:

response.headers.add('Access-Control-Allow-Origin', '*')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.