2018-12-17
This update README
is mainly to make up for the broken picture connections.
From my personal point of view, I quite like this kind of full-stack project. It is very practical. You don’t have to look at my code. You can directly write a similar todo. Although it looks very simple on the page, There are many knowledge points
koa2
to build a backend development environment that satisfies youmongodb
, complete the introduction, and understand the general use of APIVue
React
and so on. The more you write, the more proficient you will become. Required environment:安装并启动的mongodb
npm (if there is a problem with the environment, it will definitely not start)
git clone https://github.com/vkcyan/login_push.git
// 服务端
cd server
npm install
npm install start
//客户端
cd client
npm install
npm install start
Here the token is stored in localStorage
. Another way is to save it in cookie. The code may change a little, but the effect is exactly the same.
login
registry
todolist
Thoughts on routing control
router . beforeEach ( ( to , from , next ) => {
let token = localStorage . getItem ( 'token' ) // 获取token
if ( to . name == 'login' ) { // 假如登录 判断token是不是存在 存在让他跳转到主页面
verification ( token , next )
. then ( ( data ) => {
if ( data . data . type ) { // type 为1 直接跳过登录
Message ( {
showClose : true ,
message : '您已经登录,重新登录请退出账户'
} ) ;
next ( '/todolist' )
} else {
next ( )
}
} )
}
if ( to . name == 'todoList' ) {
verification ( token , next )
. then ( ( data ) => {
if ( data . data . type ) {
// type 为1说明token没有失效
// 跳转到主页面
next ( )
} else {
// token失效 强制定位到登录页面
if ( token === null ) { // 说明从来没有登陆过
Message ( {
showClose : true ,
message : '您还没有登录' ,
type : 'warning'
} )
next ( '/login' )
} else {
Message . error ( '登录信息失效' )
next ( '/login' )
localStorage . removeItem ( 'token' )
}
}
} )
. catch ( ( data ) => {
console . log ( data ) ;
} )
}
if ( to . meta . title ) {
document . title = to . meta . title
}
} )
// 验证
let verification = ( token , next ) => {
return axios . post ( '/api/verification' , { token } )
}
The backend unified verification interface /api/verification
, each routing jump determines whether the token has expired or been changed.
When the first login token does not exist, the backend must respond with 0 and pass directly.
If you are not logged in, go to the page after login. If you are not logged in, the token will be prompted separately.
if ( token === null ) { // 说明从来没有登陆过
Message ( {
showClose : true ,
message : '您还没有登录' ,
type : 'warning'
} )
next ( '/login' )
} else {
Message . error ( '登录信息失效' )
next ( '/login' )
localStorage . removeItem ( 'token' )
}
This means that login
type must be 0, through next()
The token already exists and type is 1. When accessing /todoList
, next()
Visit /login
, type is 1, jump to /todolist
, and give the user a prompt
if ( data . data . type ) { // type 为1 直接跳过登录
Message ( {
showClose : true ,
message : '您已经登录,重新登录请退出账户'
} ) ;
next ( '/todolist' )
} else {
next ( )
}