首页 > 解决方案 > 返回由 JS 承诺处理的有效 JSON 对象

问题描述

我的意图是返回 JSON 格式的实体列表,然后由客户端 JS 使用 Promises 处理。

我正在返回一个这样的 JSON 对象:

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]))

然后我使用 axios 库发出请求:

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

我曾期望该posts变量包含一个 Post 对象数组,但它却将其输出到控制台:

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

标签: javascriptpythongoogle-app-engineaxioswebapp2

解决方案


我不确定这是否能解决您的问题,但您可能错误地设置了标题。这就是我为 JSON 设置标题的方式:

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

推荐阅读