【问题标题】:Getting 400 error when using post request in Angular 4在 Angular 4 中使用发布请求时出现 400 错误
【发布时间】:2018-12-01 00:09:09
【问题描述】:

我已经编写了将请求发布到 Angular 4 中的端点的代码。这是我的代码...

import { Component, OnInit } from "@angular/core";
import { HttpClient, HttpClientModule } from "@angular/common/http";
import { HttpHeaders } from "@angular/common/http";

import "rxjs/add/operator/map";

@Component({
templateUrl: "./name.component.html",
styleUrls: ["./name.component.css"]
})

export class nameComponent implements OnInit {
constructor(private http: HttpClient) {}

ngOnInit() {
  console.log("init");
}

saveForm() {
  let names = [
    {
      name: "Bob"
    }
  ];

JSON.stringify(names);

let headers = new HttpHeaders();
headers.append("Accept", "application/json");
headers.append("Content-Type", "application/json");
headers.append("Authorization", `my_token`);

this.http
  .post("endpoint", names, {
    headers: headers
  })
  .subscribe(err => console.log(err));
}
}

这是触发 POST 调用的 html 页面上的代码

<button
 type="button"
 (click)="saveForm()"
>
Save
</button>

当我转到页面并单击按钮时,我收到 400(错误请求)错误。

message: "Http failure response for endpoint: 400 Bad Request"
name: "HttpErrorResponse"
ok: false
status: 400
statusText: "Bad Request"
url: "endpoint"

我用“端点”这个词代替了真正的网址。

我没有语法错误,但什么会触发 400?我尝试通过 LoopBack API Explorer 访问端点并且成功了。

感谢任何人能给我的帮助!

【问题讨论】:

  • 400 是Bad Request。无论端点期望什么,它都没有得到它。
  • 端点需要一个对象数组。这就是我传递给 this.http.post 调用的内容。
  • 你控制端点吗?如果没有,我会检查文档。
  • 只需对对象进行字符串化并通过 - 这很可能会解决问题
  • 如果你看一下代码,我用 JSON.stringify(names) 做到了。

标签: javascript angular http angular4-forms


【解决方案1】:

您没有保存 JSON.stringify() 的输出,因此您在进行 POST 时使用的是对象而不是字符串:

names = JSON.stringify(names);

【讨论】:

  • 现在我收到“名称是必需参数”的错误。这几乎就像当我点击 url 时,它没有看到我将对象名称作为参数传递。就像我在 POST 请求中发送了一个空对象一样。有什么想法吗?
  • 如果您使用浏览器开发人员工具检查请求,您是否看到正在发送的名称?数据是否与您使用 LoopBack API 浏览器并获得成功时发送的数据相匹配?
猜你喜欢
  • 2019-05-03
  • 2020-06-30
  • 2021-11-22
  • 1970-01-01
  • 2019-10-10
  • 2016-10-19
  • 1970-01-01
  • 2018-06-30
  • 2020-03-30
相关资源
最近更新 更多