I have an error sending a string
in my Angular service.
I tried to run my stored procedure when sending the string with Postman and everything works fine.
However, when I send the string through my service it does not work.
user.service.ts:
addUser(user: string): Observable<any> {
return this.http.post<string>('/api/user/AddUser', user)
.pipe(catchError(this.handleError));
}
Console error:
info: Microsoft.AspNetCore.Hosting.Internal.WebHost3 Request finished in 11.3875ms 400 application/json; charset=utf-8
info: Microsoft.AspNetCore.Server.Kestrel[32] Connection id "0HLL95U87FBQE", Request id "0HLL95U87FBQE:00000003": the application completed without reading the entire request body.
Browser error:
So I do not really know what the API really gets, because the result it expects must be a string of characters.
UserController C#:
[HttpPost]
public User AddUser([FromBody]string user)
{
return objUser.AddUser(user);
}
If you have a solution to my problem, I'm interested. Thank you in advance.
EDIT: By modifying my service like this:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
addUser(user: string): Observable<any> {
return this.http.post<User>('/api/user/AddUser', user.toString(), httpOptions)
.pipe(catchError(this.handleError));
}
I get this new error: Knowing that A is the first letter of the first name in the string.
I don't see any code that affects this error, the only point comes into mind is a string or JSON object need to be stringified which is differs from the Postman. SO it's better to always stringify the request body before passing it to API.
Try this:
addUser(user: string): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
var userName = JSON.stringify(user); // This
return this.http.post<user>('/api/user/AddUser', userName, httpOptions)
.pipe(catchError(this.handleError));
}