I set up a simple Ionic 5 application and a NestJS backend. Now I want to send a POST request from my application to my backend, but I always get the following error message in the browser console:
Object {headers: {…}, status: 500, statusText: "Internal Server Error", url: "http://localhost:3000/api/users", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost:3000/api/users: 500 Internal Server Error ", error: {…}} home.page.ts: 36: 14
In my NestJS backend I get this error message:
[Nest] 18696 - 03/27/2020, 10:39:04 AM [ExceptionsHandler] User validation failed: password: Path
passwordis required., Username: Pathusernameis required., Email: Path
In the network tab of the browser I get an error with the status code 500 (internal server error):
Request URL: http://localhost:3000/api/users
Request method: POST
Remote address: 127.0.0.1: 3000
Status code:
500
Version: HTTP / 1.1
Referrer Policy: no-referrer-when-downgrade
The required params are also sent correctly:
{"email":"[email protected]","username":"testname","password":"testpassword"}
The controller for my POST requests is structured like this:
@Controller('/users')
export class UsersController {
constructor(private usersService: UsersService) { }
// POST request containing the data required to create a new user
@Post()
async createUser(@Res() res, @Body() createUserDto: CreateUserDto) {
console.log('body', createUserDto);
const user = await this.usersService.create(createUserDto);
if (!user) throw new InternalServerErrorException('User could not be created!');
return res.status(HttpStatus.OK).json({
message: "User has been created successfully",
user
})
}
...
The DTO used looks like this:
export class CreateUserDto {
readonly email: string;
readonly username: string;
readonly password: string;
}
CORS is also activated in my NestJS backend. In addition, it is funny that the GET requests (via Ionic as well as via Postman or direct input into the browser) work. POST requests also work if I make them via Postman or enter them directly into the browser.
I test the POST request in this way in my Ionic application:
ngOnInit() {
this.createAccount(this.createUserDto).subscribe((res) => {
console.log('Request send', res);
}, (err) => {
console.log('Failed', err);
});
}
createAccount(credentials): Observable<any> {
return this.http.post('http://localhost:3000/api/users', JSON.stringify(credentials));
}
It is also funny that the request is not sent when I remove JSON.stringify(credentials) and enter just credentials without JSON.stringify().
What am I doing wrong here?
httpclient.postoverload is picked. Try to specify the content type as json directly and try to get it to work withoutJSON.stringify(). It should work withoutJSON.stringify()!this.http.post('http://localhost:3000/api/users', credentials, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })OPTIONSrequests?