iT邦幫忙

2021 iThome 鐵人賽

DAY 7
0
Modern Web

30天肝出購物網站系列 第 7

Day07:07 - User服務(2) - 前端 - 註冊、登入、JS正則表達式

Hi,Привет,我是Charlie!

在Day06當中,我們完成了後端的基本註冊、登入,在今天我們要完成前端的註冊跟登入囉。

================================◉‿◉=================================

首先是安裝axios,到package.json右鍵Open Terminal Here,輸入指令安裝:

*$ npm install --save axios

安裝完axios之後,到src中新增apis資料夾,在裡面新增users.js和constant.js,先在constant.js中export host跟port:

export function host(){
  return "127.0.0.1"
}

export function port(){
  return 8000
}

並在users.js中,新增發送要求到後端的方法:

import axios from 'axios'
import {host,port} from 'constant.js'

export function login(data){
  return axios.post(`http://${host()}:${port()}/login`,data)
}

export function register(data){
  return axios.post(`http://${host()}:${port()}/user`,data)
}

axios可以使用POST、PUT、DELETE等方法,只要變換axios後面的呼叫方法即可。
而中間的字串是使用JavaScript的Template System,插入變數的話是使用${}來做插入。

建立完login跟register的api方法後,先到registerPage,首先我們先把onReset方法寫齊:

onReset(){
	this.username = ""
	this.password = ""
	this.password1 = ""
	this.email = ""
	this.phone = ""
	this.address = ""
	this.usernameErrMsg = ""
	this.password1ErrMsg = ""
	this.password1ErrMsg = ""
	this.emailErrMsg = ""
	this.phoneErrMsg = ""
	this.addressErrMsg = ""
	this.isValid = true
}

接著編輯onSubmit方法,首先檢查輸入資訊的正確性:

onSubmit(e){
	e.preventDefault()
	this.isValid = true
	this.usernameErrMsg = this.passwordErrMsg = this.password1ErrMsg = this.emailErrMsg = this.phoneErrMsg = this.addressErrMsg = ""
	let UsernameValidation = /[!@#$%^&*()\-_+=|\\{}[]"'\/.,]/
	let emailValidation =  /^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]+$/
	if(UsernameValidation.test(this.username)){
	  this.usernameErrMsg = "用戶名包含特殊字元"
	  this.isValid = false
	}
	if(!emailValidation.test(this.email)){
	  this.emailErrMsg = "電子信箱格式不正確"
	  this.isValid = false
	}
	if(this.password != this.password1){
	  this.passwordErrMsg = "密碼不一致"
	  this.isValid = false
	}
	if(this.password.length < 6){
	  this.passwordErrMsg = "密碼長度過短"
	  this.isValid = false
	}
	if(this.phone.length != 10){
	  this.phoneErrMsg = "電話錯誤"
	  this.isValid = false
	}
	if(!this.isValid){
	  console.log("非法")
	}else{
	  console.log("合法")
	}
},

https://ithelp.ithome.com.tw/upload/images/20210921/2014166662fdXabsMF.png

在改寫合法後傳送的程式前,我們需要建立常量,在constant中建立以下的程式碼:

// eslint-disable-next-line no-unused-vars
export const STATUS_OK = 200
// eslint-disable-next-line no-unused-vars
export const CREATED = 201
// eslint-disable-next-line no-unused-vars
export const UNAUTHORIZED = 401
// eslint-disable-next-line no-unused-vars
export const BAD_REQUEST = 400
// eslint-disable-next-line no-unused-vars
export const METHOD_NOT_ALLOWED = 405
// eslint-disable-next-line no-unused-vars
export const INTERNAL_SERVER_ERROR = 500

這裡的注釋是避免no-unused-vars被報error。

接著在register當中引用,並引用api\users.js中的register:

import { CREATED } from '@/apis/constant.js'
import { register } from '@/apis/users.js'

if(this.isValid){
  var data = {
    "username":this.username,
    "email":this.email,
    "password":this.password,
    "password1":this.password1,
    "phone":this.phone,
    "address":this.address
  }
  register(data).then((response) => {
    if(response.data.code == CREATED){
      alert("註冊成功!")
    }else{
      alert(response.data.data)
    }
  })
}

這時候按下去就會發現:
https://ithelp.ithome.com.tw/upload/images/20210921/20141666l4sw6aPq0a.png
https://ithelp.ithome.com.tw/upload/images/20210921/20141666Rg4sGWxszH.png

出現了跨域問題!這個必須要在django方設置,在django的settings.py中新增以下幾行:

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
    'GET',
    'PUT',
    'OPTIONS',
    'POST',
    'DELETE',
    'PATCH', 
)

CORS_ALLOW_HEADERS = (
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'HTTP_AUTHORIZATION',
    'accept',
    
)

並在middleware當中設置:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

再重啟一次server,試著註冊一次:
https://ithelp.ithome.com.tw/upload/images/20210921/201416669NQ6W1sAXa.png

接著是登入的部分,在login當中先引入login:

import { login } from '@/apis/users.js'

接著寫驗證程式:

onSubmit(e){
e.preventDefault()
var data = {
  "username":this.username,
  "password":this.password
}
login(data).then((response) => {
  if(response.data.code == STATUS_OK){
    alert("登入成功!")
  }else{
    alert(response.data.data)
  }
})
},

測試:
https://ithelp.ithome.com.tw/upload/images/20210921/201416669fIcZeJnji.png

接著我們要取代掉alert,這裡要使用的是vue-simple-alert,首先先安裝:

*$ npm install --save vue-simple-alert

接著在main.js的地方引入vue-simple-alert並且use:

import VueSimpleAlert from "vue-simple-alert"

Vue.use(VueSimpleAlert)

我們login跟register這邊只要用alert跟confirm就好,將alert的地方改寫為:

this.$alert("註冊成功 | 登入成功 ….")

this.$confirm(response.data.data)

就可以把alert去掉了。

img

================================◉‿◉=================================

Day07結束了!今天我們完成了基本的登入跟登出,Day08當中將講到JWT token跟修改個人資料,See ya next day!


上一篇
Day06:06 - User服務(1) - 後端 - 註冊、登入、Python正則表達式
下一篇
Day08:08 - User服務(3) - 後端 - JWT token、修改個人資料
系列文
30天肝出購物網站30

尚未有邦友留言

立即登入留言