javascript - 在 Angular 4 中使用发布请求时出现 400 错误

标签 javascript angular http angular4-forms

我已经编写了代码来将请求发布到 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"

我用“端点”这个词代替了真实的 url。

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

我很感激有人能给我的任何帮助!

最佳答案

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

names = JSON.stringify(names);

关于javascript - 在 Angular 4 中使用发布请求时出现 400 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53566562/

相关文章:

javascript - 将当前变量与前一个变量相加

javascript - 使用 Mongoose 迭代数据库条目中的变量

angularjs - Angular 谷歌地图 (AGM) 自动完成

javascript - 应该如何将数据推送到数组中过滤对象的一部分?

html - 如果外部包含的文件(例如 JavaScript 或 CSS)在页面上包含两次(或更多次),是否会有两次(或更多次)网络请求?

http - 通过 Drive API 从 URL 上传图片

javascript - jQuery请求一个url列表同时限制并发请求的最大数量

javascript - 三星智能电视 - SEF 与 PNaCL

angular - 'p-header' 在 PrimeNg for Angular2 应用程序中不是已知元素

javascript - Angular 中的 JWT 表现不佳——出现无效 header 错误