用户注册

修改 index.ts

  1. import * as Koa from 'koa';
  2. import * as OtherParser from 'koa-better-body';
  3. import * as bodyParser from 'koa-bodyparser';
  4. // import * as Router from 'koa-better-router';
  5. import * as Convert from 'koa-convert';
  6. import { api, router } from './router';
  7. const app = new Koa();
  8. app
  9. .use(Convert(bodyParser()))
  10. .use(Convert(OtherParser()))
  11. .use(router.middleware())
  12. .use(api.middleware())
  13. .listen(3000, () => {
  14. console.log("Server Stared on http://localhost:3000");
  15. api.getRoutes().forEach((route) => {
  16. console.log(`${route.method} http://localhost:3000${route.path}`)
  17. })
  18. });

同样在src下面增加 router.ts 用来控制路由

  1. import * as Router from 'koa-better-router';
  2. import UserController from './controller/user';
  3. import * as Koa from 'koa';
  4. const router = Router().loadMethods();
  5. const api = Router({ prefix: '/api/v1' });
  6. api.get('/register', UserController.register);
  7. api.post('/register', UserController.register);
  8. // api.addRoute('GET', 'register', UserController.register);
  9. api.extend( router );
  10. export { api, router }

在 src 创建controller文件夹,再新建 user.ts

  1. import * as Koa from 'koa';
  2. import UserUtil, { User } from '../model/user';
  3. export default {
  4. async register(ctx: Koa.Context, next) {
  5. try{
  6. const { username, email, password } = ctx.request.fields
  7. try{
  8. const user = await UserUtil.createUser({
  9. username,
  10. email,
  11. password
  12. });
  13. ctx.body = JSON.stringify(user);
  14. }catch (e){
  15. console.error(e);
  16. ctx.status = 422;
  17. ctx.body = '[Unprocesable entity] \n验证失败,' + e.errors[0].message;
  18. }
  19. }catch(e){
  20. console.error(e);
  21. ctx.status = 422;
  22. ctx.body = '[Unprocesable entity] \n验证失败,必须传递 username/email/password 三个字段';
  23. }
  24. await next();
  25. }
  26. }

假如你想测试一下有没有成功,可以用postman测试一下,必须要以formdata的方式传递参数。

增加登陆逻辑

controller/user.ts

这里我们提取了一些公共方法出来用来减少代码量,返回的时候不要把密码返回给用户。

JSON.parse(JSON.stringify(user)) 用于深复制,起初我只是简单的 JSON.stringify ,我想当然的认为已经是一个新对象了,结果password就是删除不掉。

  1. import * as Koa from 'koa';
  2. import UserUtil, { User } from '../model/user';
  3. import * as ph from 'password-hash';
  4. function getFields(ctx: Koa.Context, next) : [string, string, string]{
  5. try{
  6. const { username, email, password } = ctx.request.fields
  7. return [username, email, password];
  8. }catch(e){
  9. console.error(e);
  10. ctx.status = 422;
  11. ctx.body = '[Unprocesable entity] \n验证失败,必须传递 username/email/password 三个字段';
  12. }
  13. }
  14. function exceptPassword(user: any){
  15. user = JSON.parse(JSON.stringify(user));
  16. if(user.password) delete user.password;
  17. return user;
  18. }
  19. export default {
  20. async register(ctx: Koa.Context, next) {
  21. const [username, email, password] = getFields(ctx, next);
  22. try{
  23. const user = await UserUtil.createUser({
  24. username,
  25. email,
  26. password
  27. });
  28. ctx.body = exceptPassword(user);
  29. }catch (e){
  30. console.error(e);
  31. ctx.status = 422;
  32. ctx.body = '[Unprocesable entity] \n验证失败,' + e.errors[0].message;
  33. }
  34. await next();
  35. },
  36. async login(ctx: Koa.Context, next) {
  37. const [_, email, password] = getFields(ctx, next);
  38. ctx.status = 400;
  39. try{
  40. const db_user = await User.findOne({
  41. where: {
  42. email
  43. }
  44. });
  45. if(ph.verify(password, db_user.password)){
  46. ctx.status = 200;
  47. ctx.body = exceptPassword(db_user);
  48. }else{
  49. ctx.body = "密码不正确";
  50. }
  51. }catch(e){
  52. ctx.body = e.errors[0].message;
  53. }
  54. await next();
  55. }
  56. }

在 router.ts 增加路由

  1. api.post('/login',UserController.login);