简体   繁体   English

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

[英]Angular http request with body and headers

I am trying to access https://grocerybear.com/#docs sample api request which is shown in the documentation as我正在尝试访问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

I used a website online to convert this into a javascript fetch function and got this:我使用在线网站将其转换为 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"
})

I tested this with javascript with my developer key and it worked, however I want to use the http methods in Angular 9 to get the data.我使用 javascript 和我的开发人员密钥对此进行了测试,并且它有效,但是我想使用 Angular 9 中的 http 方法来获取数据。

I tried this:我试过这个:

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);
}

and it returned a 400 error when I tried to log it to the page.当我尝试将其记录到页面时,它返回了 400 错误。

When I changed it to a post method request instead of a get method then it also returns a 400 error.当我将其更改为 post 方法请求而不是 get 方法时,它也会返回 400 错误。

Does anybody know how to implement this to get the proper data back?有谁知道如何实现这一点以获取正确的数据?

Thanks!谢谢!

I just figured it out!我刚刚想通了!

the correct code would've been:正确的代码是:

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