我已经编写了将请求发布到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));
}
}
这是我在html页面上触发POST调用的代码
<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"
我用单词“ endpoint”代替了真实的URL。
我没有语法错误,但是什么会触发400?我尝试通过LoopBack API资源管理器访问端点,并且有效。
我很感谢别人能给我的帮助!
答案 0 :(得分:0)
您没有保存JSON.stringify()的输出,因此在进行POST时使用的是对象而不是字符串:
names = JSON.stringify(names);