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