'I can't send data using ```http.post```
So When I try to send a post request to backend I get ```response code:500`` and data object received on the API side is empty I have tried using postman for same and it works just fine.
return htpp.post(link,data,headers).subscribe(response=>{
console.log(response);
},
error=>{
console.log(error);
});```
this is my function call for the same
Solution 1:[1]
The HTTP status code 500 is a generic error response and when the error comes from front-end developer you must check or/and do these steps:
- Check body request and its properties (the name of properties from front-end team must be the same what back-end team expect)
- Reload the web page. You can do that by selecting the refresh/reload button, pressing F5 or Ctrl+R
- Clear your browser's cache. If there's a problem with the cached version of the page you're viewing, it could be causing HTTP 500 issues
- Delete your browser's cookies. Some 500 Internal Server Error issues can be corrected by deleting the cookies associated with the site you're getting the error on. After removing the cookie(s), restart the browser and try again.
GOOG LUCK
Solution 2:[2]
I'm facing the same issue. I'm new to Angular and TypeScript.
I've discovered that the error occurs because the name of the variables when the post is executed its different from the expected in the API. When an http POST request is executed, the variable names are sent with an "underscore" prefix, because the naming conventions used in JS and TS.
In my case, my API is expecting a field called "{description:string}", but in the request body sent from my angular client it sends "_description: Some description" instead "description: Some description", then in my API its raised an NullPointerException because the request body is null.
If I try to send manually the request body with the correct field names without underscore "{description:Some description}" the request succeed!
let data = {description: 'some description'}
this.http.post(`${this.baseUrl}/api`, data, {headers: {'Content-Type':"application/json"}});
In my Class the object is declarated like this:
export class SomeExampleClass{
constructor(private _description: string ) {
}
get description(): string {
return this._description;
}
set description(value: string) {
this._description = value;
}
Then, when I execute the http Post request like this:
let data = new SomeExampleClass("some description")
this.http.post(`${this.baseUrl}/api`, data, {headers: {'Content-Type':"application/json"}});
console.log(data)
The log result is:
Object {_description: "some description"}
And then the Error 500 happens because the request body sent doesn't matches with the expected in the API.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bahaa Bakri |
| Solution 2 | Valmir Ademar Weide Knasel Jr |
