Templee_0216) 401 Unauthorized ~ 400 Bad Request

오범준·2021년 2월 15일
0

Below is the Current SQ

Backend is opened under address 'localhost : 3001'

Frontend is opened under address 'localhost : 3000 ',
and it is sending POST request

1. 401 UnAuthorized

    axios.post('http://localhost:3001/teams', 
      {
        name : newTeamName ,
        created : new Date()
      }
    ).then(res => console.log(res))

Error : POST http://localhost:3001/teams 401 (Unauthorized)

It describes that PB might be firstly related with Front-End side

Trial 1 : Clearing the Cache

Nope

Nope

Trial 3 : LogIn and Logout

Sometimes this Error can be seen, when you are trying to access data with being LogedIn that is only allowed under LogIn Status

Solved...to some extent

Below was the backend Nest.js Server

  @Post()
  @UseGuards(JwtAuthGuard)
  async create(
    @Body() createTeam: CreateTeamDto,
    @Member() member: MemberEntity,
  ): Promise<TeamDto> {
    console.log("request comming in")
    const team = await this.teamsServices.create(createTeam, member);
    return team.toResponseObject();
  }

As you can see above, you can see that, we are only allowing logged in user to proceed according request, by the usage of 'JwtAuthGuard'

If I remove below code, 401 Error is Gone ...But 400 Error Appeared

@UseGuards(JwtAuthGuard)

2. 400 Bad Request

400 Error usually appears when Server decliene to process the requests from the client due to wrong request

Nope

Trial 2 : Checking the interface of Body sent to Server

axios.post('http://localhost:3001/teams', 
      {
        name : newTeamName ,
        created : new Date()
      }
    ).then(res => console.log(res))

As we can see above , we were sending 2 properties througth the Body
1) name : string
2) created : Date

BUT

if you see the Backend Server, Backend was validating Body of request as below

import { IsNotEmpty, IsString } from 'class-validator';

export class CreateTeamDto {
  @IsNotEmpty()
  @IsString()
  name: string;
}

That is, it was only allowing 'name' property for 'Body'

this is why Server judged the Request as inproper request, since it did not fit the required format of Body

So if we remove 'created' property from the 'body' , Error will be gone

profile
Dream of being "물빵개" ( Go abroad for Dance and Programming)

0개의 댓글