后端
端口在3000 使用jsonwebtoken和koa-jwt生成令牌并返回 对’/api/userinfo’端口,先验证令牌是否通过,若通过返回数据
const Koa = require ( 'koa' ) ;
const Router = require ( 'koa-router' ) ;
const jwt = require ( 'jsonwebtoken' ) ;
const jwtAuth = require ( 'koa-jwt' ) ;
const secret = 'odd marron' ; const app = new Koa ( ) ;
const router = new Router ( ) ; router. get ( '/api/login' , async ctx => { const { username, passwd } = ctx. query; console. log ( username, passwd) ; if ( username === 'admin' && passwd === '123456' ) { const token = jwt. sign ( { data: { name: '好吃的栗子' } , exp: Math. floor ( Date. now ( ) / 1000 ) + 60 * 60 } , secret) ; ctx. body = { code: 1 , token } ; } else { ctx. status = 401 ; ctx. body = { code: 0 , message: '用户名或密码错误' } ; }
} ) ; router. get ( '/api/userinfo' , jwtAuth ( { secret } ) , async ctx => { ctx. body = { code: 1 , data: { name: '栗子' , age: 18 } } }
) app. use ( router. routes ( ) ) ;
app. listen ( 3000 , ( ) => { console. log ( '[server] server is runnint at http://127.0.0.1:3000' ) ;
} ) ;
前端
运行在8080端口,故产生了跨域 在vue.config.js中添加代理 对所有’/api’开头的请求进行代理
configureWebpack: { devServer: { proxy: { '/api' : { target: 'http://127.0.0.1:3000' , changeOrigin: true } } }
}