【问题标题】:How to use Body parameter In an API Post request using Typescript如何在使用 Typescript 的 API Post 请求中使用 Body 参数
【发布时间】:2019-06-15 03:25:53
【问题描述】:

我想知道如何使用打字稿将正文添加到 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)
  })
}

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

【问题讨论】:

  • post 方法的第二个参数是正文,您将密钥正文包含在正文中。您还需要查看如何发送未序列化为 JSON 的 url 编码,这是默认设置。
  • HTTP 示例请求 POST /oauth2/token HTTP/1.1 主机:api.channeladvisor.com 授权:基本 MTIzNDU6YWJjZGU= 内容类型:应用程序/x-www-form-urlencoded 缓存控制:否-缓存grant_type=refresh_token&refresh_token=acCD58Efghijk1L7mn-OPq0rTqOb5oRsTUvwxyZabcD
  • 他们也给出了这种方式,但我应该在哪里包含这部分:grant_type=refresh_token&refresh_token=acCD58Efghijk1L7mn-OPq0rTqOb5oRsTUvwxyZabcD –

标签: angular typescript api http bad-request


【解决方案1】:

您有以下身体要求:

  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
  }},

将发送带有 json 格式正文的 content-type application/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'
    }})

【讨论】:

  • 我试过了,但我仍然收到 404 错误请求。还有其他方法可以包含身体吗?
猜你喜欢
  • 1970-01-01
  • 2015-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-03
  • 2019-06-07
  • 1970-01-01
相关资源
最近更新 更多