【发布时间】: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