javascript - 返回由 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
解决方案
我不确定这是否能解决您的问题,但您可能错误地设置了标题。这就是我为 JSON 设置标题的方式:
self.response.headers["Content-Type"] = "application/json; charset=utf-8"
推荐阅读
- gitlab - Gitlab CICD在生产环境设置错误的服务url
- python - Django - request.is_secure 总是返回 False
- ios - 带有 PDF 的 UIButton 图像具有全宽图像视图
- javascript - 如何从一个组件滚动到另一个组件的元素?
- c# - 在 Mac 上不使用 DotNetZip 解压缩文件
- r - R中的for循环嵌套在另一个中
- docusignapi - 我可以放置没有锚字符串的 DocuSign 签名对象吗?
- c# - 指示泛型类型在某些情况下可以为 null 的属性
- python - Pandas:创建一个从 excel 文件中选择行的循环
- php - 如何使用 PHP 为用户创建编辑个人资料页面?