Search code examples
javascriptpythongoogle-app-engineaxioswebapp2

Returning a valid JSON object which is to be handled by JS promise


My intention is to return a list of entities in JSON format which is then handled by the client-side JS using Promises.

I am returning a JSON object like this:

from webapp2_extras import json

class AllPostsJson(webapp2.RequestHandler):
    def get(self):
        posts = Post.query().fetch()
        self.response.content_type = 'application/json'
        self.response.headers['Access-Control-Allow-Origin'] = '*'
        self.response.out.write(json.encode([p.to_dict() for p in posts]))

Then I am using the axios library to make the request:

posts = axios.get('example.com/posts-json').then(resp => resp.data)
console.log(posts) // output: Promise {<pending>}

I had expected the posts variable to contain an array of Post objects, but it outputs this to the console instead:

Promise {<pending>}
__proto__: 
Promise[[PromiseStatus]]: "resolved"
[[PromiseValue]]: undefined

Solution

  • I'm not sure if this will solve your problem, but you may be setting your header incorrectly. This is how I set my headers for JSON:

    self.response.headers["Content-Type"] = "application/json; charset=utf-8"