본문 바로가기
Research/Nest.js

nestjs_error_html formData를 axios로 서버에 전송하기

by RIEM 2023. 4. 17.

 

HTML에서 form 데이터를 보내도 빈 객체만 전달된다.

POSTMAN으로 보낼 땐 잘 되는데, 프론트 단에서 보내면 이렇게 된다. 왜그럴까?

<form id="loginForm" class="m-auto"
  style="width: 500px">
  <div class="form-group p-2">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" class="form-control" id="email"
      aria-describedby="emailHelp" placeholder="Enter email">

  </div>
  <div class="form-group p-2">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" class="form-control" id="password"
      placeholder="Password">
  </div>

  <div class="p-2">
    <button type="button" id="sendButton" class="btn btn-primary">Submit</button>
  </div>
</form>

버튼 코드는 이렇다.

 

해결

    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Axios를 사용하기 위해 HTML 바디 끝 바로 위에 axiod CDN을 추가해준다.

<form id="loginForm" class="m-auto"
  style="width: 500px">
  <div class="form-group p-2">
    <label for="exampleInputEmail1">Email address</label>
    <input name="email" type="email" class="form-control" id="email"
      aria-describedby="emailHelp" placeholder="Enter email">

  </div>
  <div class="form-group p-2">
    <label for="exampleInputPassword1">Password</label>
    <input name="password" type="password" class="form-control" id="password"
      placeholder="Password">
  </div>

  <div class="p-2">
    <button type="button" id="sendButton" class="btn btn-primary">Submit</button>
  </div>
</form>

<script>
  const emailInput = document.getElementById("email");
  const passwordInput = document.getElementById("password");
  const btn = document.getElementById("sendButton");

btn.addEventListener("click", () => {
  const email = emailInput.value;
  const password = passwordInput.value;

  axios.post("http://127.0.0.1:3000/users/login", {
      email: email,
      password: password
    })
    .then((response) => {
      console.log(response);
    });
});

</script>

axios로 email, password를 post로 전송해준다.

추가로 form input에 name 프로퍼티를 추가해줘야 한다. 내가 이 부분을 누락해서 데이터 전송에 실패한 것으로 보인다.

 

정상적으로 서버에 잘 전달되었다. 

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post('login')
  login(@Body() data) {
    console.log(data);
  }
  
  ...

서버는 body값으로 가져오고 있다.

댓글