繁体   English   中英

带有正文和标头的 Angular http 请求

[英]Angular http request with body and headers

我正在尝试访问https://grocerybear.com/#docs示例 api 请求,该请求在文档中显示为

curl -H "api-key: 123ABC" \
                     -H "Content-Type: application/json" \
                     -X POST \
                     -d '{"city":"LA", "product":"bread", "num_days": 10}' \
                     https://grocerybear.com/getitems

我使用在线网站将其转换为 javascript 获取 function 并得到了这个:

    fetch("https://grocerybear.com/getitems", {
  body: "{\"city\":\"LA\", \"product\":\"bread\", \"num_days\": 10}",
  headers: {
    "Api-Key": "123ABC",
    "Content-Type": "application/json"
  },
  method: "POST"
})

我使用 javascript 和我的开发人员密钥对此进行了测试,并且它有效,但是我想使用 Angular 9 中的 http 方法来获取数据。

我试过这个:

getData(){

    const options = {
        headers: new HttpHeaders(
        {
          "Api-Key": '(myDeveloper key was inserted here in the program)' as const,
          "Content-Type": 'application/json' as const
        }
        ),
        body: "{\"city\":\"LA\", \"product\":\"bread\", \"num_days\": 10}"
      };

    return this.http.get(`https://grocerybear.com/getitems`, options);
}

当我尝试将其记录到页面时,它返回了 400 错误。

当我将其更改为 post 方法请求而不是 get 方法时,它也会返回 400 错误。

有谁知道如何实现这一点以获取正确的数据?

谢谢!

我刚刚想通了!

正确的代码是:

getData(){
    const body = {city:"LA", product:"bread", num_days: 10}
    const options = {
        headers: new HttpHeaders(
        {
          "Api-Key": 'API KEY inserted here' as const,
          "Content-Type": 'application/json' as const
        }
        )
      };

    return this.http.post('https://grocerybear.com/getitems', body, options);
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM