【问题标题】:Angular making http post not workingAngular使http帖子不起作用
【发布时间】:2018-12-21 04:51:34
【问题描述】:

我正在尝试在 Angular 中发出 http post 请求,但不知道为什么它不起作用。

getTripEstimate(event){
    let authUsername:string = '*****';
    let authPassword:string = '*****';
    let headers = new Headers();
    let params = {
      "grant_type": "*****",
      "scope": "*****",
      "username": "*****",
      "password": "*****"
    };
    let body = JSON.stringify(params)
    console.log("body: "+body)
    this.http.post("http://localhost:8000/auth/oauth/token",{
        headers: headers,
        body: body
    }).toPromise().then(res => console.log(res.json)).catch(res => console.log("Error"))
  }

我已经注释掉了密码和用户名,但是我收到了 401 错误,并且不知道为什么我使用的凭据是正确的,因为它们是通过邮递员工作的。也许我发出的 POST 请求不正确?

【问题讨论】:

  • 您可以尝试使用 Postman 来查看是否能够在 Angular 之外创建有效的 http post 请求。然后尝试在 Angular 中复制它,看看请求是否符合 Chrome 网络开发工具。
  • 我确实这样做了。并尝试在 Angular 中进行复制,但我想我没有从上面粘贴的代码中正确地做到这一点? ^
  • 应该是new HttpHeaders()
  • 我添加了 import { HttpHeaders } from '@angular/common/http';并从 new Headers() 更改为 new HttpHeaders() 但它仍然不起作用
  • 构造函数是httpClient.post(url, body, options),选项是你的标题

标签: angular http http-post http-get


【解决方案1】:

试试这个来发帖请求

     getTripEstimate(event){
            this.http.post("http://localhost:8000/auth/oauth/token",{
      **use what ever params you want to send**
              "username": "*****",
              "password": "*****"
            },
              { headers: headers})
              .subscribe(response => {
               console.log(response);
          }

【讨论】:

    【解决方案2】:

    您没有正确构建您的请求:

    HttpClient 的正确构造函数是httpClient.post(url, body, options)

    this.http.post(
      "http://localhost:8000/auth/oauth/token",
      body,
      headers: headers
    ).subscribe(res => { console.log(res); }, error => console.log(error))
    

    【讨论】:

    • 这并没有给我一个错误,但我如何得到响应?
    • 我更新以显示如何控制台记录响应。 post() 函数返回一个 observable。你必须订阅一个 observable 才能启动它。
    • Ploppy 谢谢你,但这仍然给我一个 401 错误。无法加载 localhost:8000/auth/oauth/token:预检响应包含无效的 HTTP 状态代码 401。
    • 然后你必须在chrome网络开发工具中检查请求的header和body,以确保请求具有所有需要的参数。
    • 我也不得不做 {headers:headers} 因为只是简单地写 headers: headers 因为它需要 2-3 个参数但是这样写是 4 个参数所以我不得不做 {headers: headers}但仍然收到我上面提到的错误。
    最近更新 更多