用户注册
修改 index.ts
import * as Koa from 'koa';
import * as OtherParser from 'koa-better-body';
import * as bodyParser from 'koa-bodyparser';
// import * as Router from 'koa-better-router';
import * as Convert from 'koa-convert';
import { api, router } from './router';
const app = new Koa();
app
.use(Convert(bodyParser()))
.use(Convert(OtherParser()))
.use(router.middleware())
.use(api.middleware())
.listen(3000, () => {
console.log("Server Stared on http://localhost:3000");
api.getRoutes().forEach((route) => {
console.log(`${route.method} http://localhost:3000${route.path}`)
})
});
同样在src下面增加 router.ts 用来控制路由
import * as Router from 'koa-better-router';
import UserController from './controller/user';
import * as Koa from 'koa';
const router = Router().loadMethods();
const api = Router({ prefix: '/api/v1' });
api.get('/register', UserController.register);
api.post('/register', UserController.register);
// api.addRoute('GET', 'register', UserController.register);
api.extend( router );
export { api, router }
在 src 创建controller文件夹,再新建 user.ts
import * as Koa from 'koa';
import UserUtil, { User } from '../model/user';
export default {
async register(ctx: Koa.Context, next) {
try{
const { username, email, password } = ctx.request.fields
try{
const user = await UserUtil.createUser({
username,
email,
password
});
ctx.body = JSON.stringify(user);
}catch (e){
console.error(e);
ctx.status = 422;
ctx.body = '[Unprocesable entity] \n验证失败,' + e.errors[0].message;
}
}catch(e){
console.error(e);
ctx.status = 422;
ctx.body = '[Unprocesable entity] \n验证失败,必须传递 username/email/password 三个字段';
}
await next();
}
}
假如你想测试一下有没有成功,可以用postman测试一下,必须要以formdata的方式传递参数。
增加登陆逻辑
controller/user.ts
这里我们提取了一些公共方法出来用来减少代码量,返回的时候不要把密码返回给用户。
JSON.parse(JSON.stringify(user)) 用于深复制,起初我只是简单的 JSON.stringify ,我想当然的认为已经是一个新对象了,结果password就是删除不掉。
import * as Koa from 'koa';
import UserUtil, { User } from '../model/user';
import * as ph from 'password-hash';
function getFields(ctx: Koa.Context, next) : [string, string, string]{
try{
const { username, email, password } = ctx.request.fields
return [username, email, password];
}catch(e){
console.error(e);
ctx.status = 422;
ctx.body = '[Unprocesable entity] \n验证失败,必须传递 username/email/password 三个字段';
}
}
function exceptPassword(user: any){
user = JSON.parse(JSON.stringify(user));
if(user.password) delete user.password;
return user;
}
export default {
async register(ctx: Koa.Context, next) {
const [username, email, password] = getFields(ctx, next);
try{
const user = await UserUtil.createUser({
username,
email,
password
});
ctx.body = exceptPassword(user);
}catch (e){
console.error(e);
ctx.status = 422;
ctx.body = '[Unprocesable entity] \n验证失败,' + e.errors[0].message;
}
await next();
},
async login(ctx: Koa.Context, next) {
const [_, email, password] = getFields(ctx, next);
ctx.status = 400;
try{
const db_user = await User.findOne({
where: {
}
});
if(ph.verify(password, db_user.password)){
ctx.status = 200;
ctx.body = exceptPassword(db_user);
}else{
ctx.body = "密码不正确";
}
}catch(e){
ctx.body = e.errors[0].message;
}
await next();
}
}
在 router.ts 增加路由
api.post('/login',UserController.login);
当前内容版权归 nodelover.me 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 nodelover.me .