Home > Net >  How can I fix the error: "Cannot POST /users. StatusCode: 404" while making a POST request
How can I fix the error: "Cannot POST /users. StatusCode: 404" while making a POST request

Time:01-02

I'm following the article while working on the project.

When making a POST request in Postman:

http://localhost:3000/users

With Body request:

{
    "name": "Jose Luis",
    "lastName": "Campos Bautista"
}

I'm getting the issue as:

{
    "statusCode": 404,
    "message": "Cannot POST /users",
    "error": "Not Found"
}

Am I missing something in the steps of the article? Does it the problem related specifically to API?

Inside the controller I have annotated as users:

@Controller('users')

Before executing a Postman request, I run the command:

npm run start:dev

Also I use the Postgres database with the next format of configuration:

DB_URL=postgres://user:password@localhost:5444/dataBaseName
ENTITY_PATH=dist/**/**/*.entity{.js, .ts} 

Thanks in advance for any reasonable advice/ideas on how I can overcome this issue.

CodePudding user response:

I have looked in your git repo. You should insert some route inside your controller like this

@Post('/create')

Your service is also lacking await before calling the save method in your service. It should be like

async create(user: UserDto): Promise<UserDto> {
return await this.userRepository.save(user);
 }

and your controller should be like

 @Post()
 async create(@Body() user: UserDto): Promise<UserDto> {
 return await this.userService.create(user);
 }

You also don't have a connection initialization inside your app.module.ts so your API wouldn't be able to save data inside database.

CodePudding user response:

Your UserModule is never registered with the application. The AppModule needs to have UserModule in its imports array. Just because the file exists and is written doesn't mean Nest knows what to do with it. You have to tell the application that the module should be used by having it in the imports path of some module that eventually makes its way back to the root module (usually AppModule)


Side Note: when you do that, you will get an error from TypeORM because you call TypeormModule.forFeature() without ever importing TypeormModule.forRoot(), so just a heads up that you need to add that

  • Related