Reputation: 83
I've written code to post a request to an endpoint in Angular 4. Here is my code...
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));
}
}
This is the code I have on the html page that triggers the POST call
<button
type="button"
(click)="saveForm()"
>
Save
</button>
When I go to the page and click the button, I get a 400 (Bad Request) error.
message: "Http failure response for endpoint: 400 Bad Request"
name: "HttpErrorResponse"
ok: false
status: 400
statusText: "Bad Request"
url: "endpoint"
I substituted the word "endpoint" for the real url.
I have no syntax errors, but what could trigger a 400? I tried hitting the endpoint through LoopBack API Explorer and it worked.
I appreciate any help someone can give me!
Upvotes: 1
Views: 8121
Reputation: 1242
You're not saving the output of JSON.stringify() so you're using the object and not a string when you make the POST:
names = JSON.stringify(names);
Upvotes: 1