똑같은 삽질은 2번 하지 말자

[Vue.js] axios create, env파일, Login Validation 처리 본문

Vue

[Vue.js] axios create, env파일, Login Validation 처리

곽빵 2020. 5. 16. 17:30

axios create , env 파일 ?

API를 사용할 때, 서버 End Point(localhost:8080)들은 공통인 부분인데,

그런 URL 공통화는 axios create 의 baseURL 설정으로 할 수 있다.

import axios from 'axios';

const instance = axios.create({
  baseURL: 'http://localhost:3000/',
});

function registerUser(userData) {
  return instance.post('signup', userData);
}

export { registerUser };

 

axios create 공식 문서

https://github.com/axios/axios#axioscreateconfig

 

axios/axios

Promise based HTTP client for the browser and node.js - axios/axios

github.com

env파일로 서버의 EndPoint URL관리 방법

 

접두에 VUE_APP_이 붙어있으면 자동로드 / 설정파일 변경시에는 서버 재로드 필요

(Vue CLI 3.0 이후부터 가능)

const instance = axios.create({
  baseURL: process.env.VUE_APP_API_URL,
});

이렇게 불러주면 된다.

 

그리고 개발용 배포용으로 환경설정을 파일을 관리하는게 좋은데

.env.production 와 .env.development로 관리할 수 있는데,

<!-- .env.production(npm run build)  .env.development(npm run serve) -->  

기본 .env는 .env.production이나 .env.development가 없을때, 우선순위가 돌아온다.

 

Vue CLI env파일 규칙 문서

https://cli.vuejs.org/guide/mode-and-env.html#modes-and-environment-variables

 

Modes and Environment Variables | Vue CLI

Modes and Environment Variables Modes Mode is an important concept in Vue CLI projects. By default, there are three modes: development is used by vue-cli-service serve test is used by vue-cli-service test:unit production is used by vue-cli-service build an

cli.vuejs.org

 

Validation 처리

Validation is a method to authenticate the user. JavaScript provides the facility to validate the form on the client-side so data processing will be faster than server-side validation. It is preferred by most of the web developers. Through JavaScript, we can validate name, password, email, date, mobile numbers and more fields.

 

간단하게 email형식으로 입력했는지 validation처리를 해보자

javascript email validation 치면 해당하는 regular expression이 나온다.

 

function validateEmail(email) {
  var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).toLowerCase());
}
export { validateEmail };

 

해당 식을 이용해서 

v-bind:disabled 디렉티브 와 computed에서 validation check 함수를 만들어준다.()

https://medium.com/@jeongwooahn/vue-js-watch%EC%99%80-computed-%EC%9D%98-%EC%B0%A8%EC%9D%B4%EC%99%80-%EC%82%AC%EC%9A%A9%EB%B2%95-e2edce37ec34

 

[Vue.js] watch와 computed 의 차이와 사용법

Vue.js에서 computed 프로퍼티는 매우 유용하게 사용된다. 그러나 처음 Vue.js를 시작할때 computed와 watch가 모두 반응형이라는 키워드과 관련이 있기 때문에 이 둘을 혼동하곤 했다. Vue.js의 강점을 잘 �

medium.com

혹시나 computed의 작동방식이 잘 기억안날때, 체크 ㄱ

 

<template>
  <form @submit.prevent="submitForm">
    <div>
      <label for="username">id: </label>
      <input id="username" type="text" v-model="username" />
    </div>
    <div>
      <label for="password">password: </label>
      <input id="password" type="text" v-model="password" />
    </div>
    <button v-bind:disabled="!isUsernameValid || !password" type="submit">
      로그인
    </button>
    <p>{{ logMessage }}</p>
  </form>
</template>

<script>
import { loginUser } from '@/api/index.js';
import { validateEmail } from '@/utils/validation.js';
export default {
  data() {
    return {
      username: '',
      password: '',
      logMessage: '',
    };
  },
  computed: {
    isUsernameValid() {
      return validateEmail(this.username);
      //username이 한글자 한글자 바뀔때마다 실행
    },
  },
  methods: {
    async submitForm() {
      try {
        // 비즈니스 로직
        const userdata = {
          username: this.username,
          password: this.password,
        };
        const { data } = await loginUser(userdata);
        this.logMessage = data.message;
      } catch (error) {
        // 에러 핸들링헐 코드
        this.logMessage = error.response.data;
      } finally {
        this.initForm();
      }
    },
    initForm() {
      this.username = '';
      this.password = '';
    },
  },
};
</script>

 

Comments