Shrey
Shrey

Reputation: 156

Why is POST response printing undefined?

I am trying to build a chrome extension and when I get the JSON response from the Flask endpoint it prints correctly in my scipt as {"rating": 3.5}. But when I try to access rating using resp.rating and resp["rating"] they both return undefined. Here is the code in my Flask script

import json
from flask import Flask, request
from flask_cors import CORS
from clean import clean_comment
from textblob import TextBlob

app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'application/json'

@app.route("/predict/", methods=["GET", "POST"])
def predict():
    comments = []
    rating = 0
    
    if request.method == "POST":
        comments = request.json["comments"]
    for comment in comments:
        temp = TextBlob(clean_comment(comment)).sentiment.polarity
        print(clean_comment(comment) + ": " + str(temp))
        rating += temp

    if rating > 0:
        rating = (((rating/len(comments) + 1) / 2) * 5) * 1.2
    if rating >= 5:
        rating = 5.0
    print(rating)
    return json.dumps({"rating": str(rating)})

Here is how I am accessing it

chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {
    if (request.message === "activate_icon") {
        chrome.tabs.query({active:true,windowType:"normal", currentWindow: true}, function(d){
            chrome.pageAction.show(d[0].id);
        })
    }
    if(request.comments) {
        $.ajax({
            type: 'POST',
            contentType: 'application/json',
            headers: {"Access-Control-Allow-Origin":"*"},
            url: "http://127.0.0.1:5000/predict/",
            data: JSON.stringify({'comments': request.comments}),
            success: function(resp) {
                // this is where console.log(resp.rating) and console.log(resp["rating"]) return
                // undefined but console.log(resp) returns the correct output
                chrome.runtime.sendMessage(resp)
            }
        });
    }
});

Upvotes: 0

Views: 309

Answers (2)

yuxiaoy
yuxiaoy

Reputation: 244

With newer flask version, actually you can return the data as below, without using jsonify or Response:

return {'rating': str(rating)}

Flask would add right headers for you automaticly.

Upvotes: 0

GAEfan
GAEfan

Reputation: 11360

json.dumps() is not a valid http response. I think you want:

from flask import Flask, request, Response

return Response(json.dumps({"rating": str(rating)}), mimetype='application/json')

Upvotes: 2

Related Questions