【问题标题】:Why doesn't my fronend Javascript show the same response from API as browser? [duplicate]为什么我的前端 Javascript 显示的 API 响应与浏览器不同? [复制]
【发布时间】:2021-02-19 22:01:43
【问题描述】:

我的 Flask 后端带有一个链接到 Stripe API 的 API 函数。当我在 Postman 或浏览器中调用它时,我得到的正是我所期望的(Stripe 生成的 URL)。然而,当我在我的 Javascript 代码中调用它时,我得到了完全不同的东西,我不知道为什么。

这是我在 Flask/Python 中的代码:

@app.route('/manage-subscription-portal', methods=['GET'])
def manageSubscriptionPortal():
  portalTry = stripe.billing_portal.Session.create(
      customer='cus_XXXXXXXXXXX',
      return_url='https://example.com/account',
  )  
  print(portalTry["url"])
  return jsonify({'url' : portalTry["url"]})

当在 Postman 中调用时,我会得到这个响应(这是我所期望的)

{
  "url": "https://billing.stripe.com/session/_ILW65rxo7ix3RLm3SBrZ9PQeDV7pHlm"
}

这是我链接到按钮的 Javascript 代码

 manageSubscription.addEventListener("click", function(){
    fetch('/manage-subscription-portal').then(response => {
      console.log(response)
      return response
    }).then(portalSession => {
      console.log(portalSession)
    })
  })

'response' 和 'portalSession' 都给出了图片中显示的内容

有谁知道为什么我的 Javascript 代码与 Postman 中的不一样?

【问题讨论】:

    标签: javascript python api flask api-design


    【解决方案1】:

    您好,如果您使用的是 HTML5 fetch API,您可以像这样从服务器访问返回的 JSON

    manageSubscription.addEventListener("click", function(){
      fetch('/manage-subscription-portal').then(response => {
        return response.json() 
      }).then(portalSession => {
        console.log(portalSession)
      })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-30
      • 2023-01-21
      • 2019-05-29
      • 2014-03-31
      • 2018-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多