Vue.js
vue.js [로그인]
z00h
2022. 6. 10. 19:40
댓글기능까지 모두 만들고 이제 통합으로 회원가입, 로그인 하는 기능을 만들려고한다.
기존의 backend에서 기능을 만들고 PostMan으로 회원가입을 시켜 놓은 상태이고 DB에 member가 저장되어 있는 상태이고 우선 vue에서 login.vue를 만들고 로그인 기능부터 만들 예정이다.
ui는 다음과 같이 만들었고 로그인을 할 시 토큰이 생성되면 그것을 가져와
Home.vue에 토큰 실어주도록 할 것이다.
Login.vue
<template>
<v-app id="app">
<v-main>
<v-container
style="position: relative; top: 20%; margin-left: 20%"
class="text-xs-center"
>
<v-layout row wrap class="text-xs-center">
<v-flex>
<v-card flat class="mx-auto" max-width="800">
<v-row style="margin-top: 60px">
<v-col>
<v-form style="width: 400px; height: 300px">
<div class="mx-3">
<v-icon color="black" size="30px"></v-icon>
userId
<div class="mx-1">
<v-text-field
placeholder="userId"
v-model="userId"
required
></v-text-field>
</div>
</div>
<div class="mx-3">
<v-icon color="black" size="30px"></v-icon>
userPassword
<div class="mx-1">
<v-text-field
placeholder="userPassword"
type="password"
v-model="userPassword"
required
></v-text-field>
</div>
</div>
<v-card-actions>
<v-btn
color="#2c4f91"
dark
large
block
@click="loginSubmit"
>Login</v-btn
>
</v-card-actions>
</v-form>
</v-col>
</v-row>
</v-card>
</v-flex>
</v-layout>
</v-container>
</v-main>
</v-app>
</template>
<script>
export default {
data() {
return {
userId: "zoo@gmail.com",
userPassword: "qwer!23",
token:''
};
},
methods: {
loginSubmit() {
let Data = {};
Data.email = this.userId;
Data.password = this.userPassword;
this.$axios.post("/authenticate", JSON.stringify(Data), {
headers: {
"Content-Type": `application/json`,
Authorization: '',
},
}).then((res) => {
console.log(res)
if (res.status === 200) {
this.$store.commit("login", res.data);
this.$router.push("이동할 페이지 path");
// 로그인 성공시 처리해줘야할 부분
}
});
},
},
};
</script>
http://localhost:8081/#/Login에서 로그인을 해보면 정상적으로 data에 토큰이 생성된 것을 볼 수있고
그 토큰을 담아서 Home.vue를 볼 수 있도록 헤더에 토큰을 실어 주었다.
Home.vue의 url의 헤더에 토큰을 실어주니 원래 401에러가 떴는데 정상적으로 Home을 볼 수 있게 되었다!
참고한 블로그:
기록
dwc04112.tistory.com
https://developerjournal.tistory.com/15?category=912023
[Vue.js] 로그인 기능 구현하기
Vue.js로 로그인을 하기 위해서 프론트측에서는 로그인 하기 위한 view와 상태관리를 할 수 있는 store(Vuex)가 필요하다. Vuex 관련 내용은 아래 글을 참고하길 바란다. (물론 Vuex를 사용하지 않고도
developerjournal.tistory.com