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값으로 가져오고 있다.
'Research > Nest.js' 카테고리의 다른 글
nestjs_에러해결_DTO validation 작동이 되지 않는 문제 (0) | 2023.04.26 |
---|---|
nestjs_실패로그_프로젝트 docker 환경변수 설정 문제 (1) | 2023.04.26 |
nestjs_RDS Postgres 인스턴스 생성 및 nestjs 모듈 설치 (0) | 2023.04.15 |
nestjs_view 엔진 적용하기(hbs) (0) | 2023.04.13 |
nestjs_특정 버전으로 nest 설치하는 방법 (0) | 2023.04.12 |
댓글