首页 > 解决方案 > 如何在使用 Typescript 的 API Post 请求中使用 Body 参数

问题描述

我想知道如何使用打字稿将正文添加到 api 请求中。我已经在邮递员上完成了这个请求,我得到了回复,但是我不知道如何使用打字稿来完成。我不断收到“错误请求”。我检查了主机的 api 文档,他们向我展示了如何做到这一点:

Request Format
POST https://api.channeladvisor.com/oauth2/token

Authorization: Basic [application id:shared secret]
Content-Type: application/x-www-form-urlencoded
Body: grant_type = refresh_token &
      refresh_token = [refresh token]

我有刷新令牌和授权详细信息。所以我尝试在打字稿中这样做:

this.http.post('https://api.channeladvisor.com/oauth2/token',                    
  {body:{
    grant_type:"refresh_token",
    refresh_token:this.refresh_token
  }},

  {headers:{
    'Authorization':this.token
    }})
.subscribe((response)=>{
    this.new_token=response;
    console.log("This is the new token")
      console.log(this.new_token)
  })
}

但是当我运行它时,我得到一个错误的请求错误。我认为它与语法有关。

标签: angulartypescriptapihttpbad-request

解决方案


你有以下身体要求:

  grant_type = refresh_token &
  refresh_token = [refresh token]

具有内容类型application/x-www-form-urlencoded

错误

你的代码:

this.http.post('https://api.channeladvisor.com/oauth2/token',                    
  {body:{
    grant_type:"refresh_token",
    refresh_token:this.refresh_token
  }},

content-type application/json使用 json 格式的正文发送。

使固定

固定代码:

this.http.post('https://api.channeladvisor.com/oauth2/token',                    
  {body:`
    grant_type = refresh_token &
    refresh_token = ${something}
  `},
  {headers:{
    'Authorization':this.token,
    'Content-Type':'application/x-www-form-urlencoded'
    }})

推荐阅读