【问题标题】:Returning a valid JSON object which is to be handled by JS promise返回由 JS 承诺处理的有效 JSON 对象
【发布时间】:2018-10-12 19:18:10
【问题描述】:

我的意图是返回一个 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

【问题讨论】:

    标签: javascript python google-app-engine axios webapp2


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 2020-01-04
    • 1970-01-01
    • 2021-07-22
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 2017-12-14
    相关资源
    最近更新 更多