How to render_template() in Flask after fetching request from Java Script?

Viewed 263

I'll try to explain my problem as well as I can. I've got an web application. I need to pass some data in JSON from Java Script to Flask's endpoint. To do this I use Fetch API. The data is passing to the endpoint as I want, I can print it in python's console, so I'm sure that it works properly. Here is the code of JS posting:

        var data = {
            x: 3
        };          
        
        fetch('/correctInvoice', {
            method: 'POST',
            body: JSON.stringify(data)
        })
        .then(function (response) {
            if (response.status !== 200) {
                console.log(`Status code: ${response.status}`);
                return;
            }
            response.json().then(function (data) {
                console.log(data);
            });
        })
        .catch(function (error) {
            console.log("Error: " + error);
        });

and my '/correctInvoice' endpotins looks like this:

@app.route('/correctInvoice', methods = ['POST'])
def correctInvoice():
     x = request.get_json(force = True)
     print("type of: " + str(type(x)))
     print(x)
     res = make_response(jsonify(x), 200)
     return res

My problem is that returning res causes makeing response to fetch API in JS, and I need to show it in a browser like it would happen without request.get_json(force = True). I just need to see this JSON in a browser, and I compleatly have no idea how to do this.

Thanks in advance! ;)

1 Answers

i think this will help in returning JSON reponse in browser

return jsonify(res) # replace it with "return res"

lastline in your endpoint

Related