node no koa

1. Middleware

1.1 @koa/cors

Middleware to solve cross-domain problems.

npm i @koa/cors -S

https://www.npmjs.com/package/@koa/cors

1.2 also-body

Handle request data for post requests and file uploads.

npm i koa-body -S

1.3 koa-static

Request static resource middleware.

Requests are generally divided into two types:

  1. Static resources: pictures, style files, script files, etc.
  2. Dynamic resources: resources that need to be looked up in the database.
npm i koa-static -S

1.4 joy-router

Routing middleware.

npm i koa-router -S

1.5 chalk

An npm package that modifies the terminal log style.

npm i chalk -S

2. Examples

2.1 default-config.js

const DEFAULT_OPTION = {
    
    
  baseUrl: '/',
  method: 'post',
  port: '8888'
}

const FORMAT = {
    
    
  codeKey: 'code',
  msgKey: 'msg',
  dataKey: 'data',
  succCode: '000000',
  timeoutCode: '299999'
}

module.exports = {
    
    
  defaultOption: DEFAULT_OPTION,
  format: FORMAT
};

2.2 util

// 格式化成功的响应数据格式
function succ(data = {
    
    }, message = '交易处理成功...') {
    
    
  const format = this.format;
  let response = {
    
    
    [format.codeKey]: format.succCode,
    [format.msgKey]: message
  };
  if (format.dataKey) {
    
    
    return {
    
    
      ...response,
      [format.dataKey]: data
    };
  }
  return {
    
    
    ...response,
    ...data
  };
}
// 格式化失败的响应数据格式
function fail(failCode, data = {
    
    }, message = '交易处理失败...') {
    
    
  const format = this.format;
  const response = {
    
    
    [format.codeKey]: failCode,
    [format.msgKey]: message
  };
  if (format.dataKey) {
    
    
    return {
    
    
      ...response,
      [format.dataKey]: data
    };
  }
  return {
    
    
    ...response,
    ...data
  }
}

module.exports = function (options) {
    
    
  return {
    
    
    succ: succ.bind(options),
    fail: fail.bind(options)
  }
};

2.3 server.js

const Koa = require('koa');
const KoaRouter = require('koa-router');
const koaCors = require('@koa/cors');
const koaBody = require('koa-body');
const {
    
    cyan} = require('chalk');
const {
    
    defaultOption, format} = require('./default-config');
const util = require('./util')({
    
    ...defaultOption, format});

let app = new Koa();
let koaRouter = new KoaRouter();
// 处理路由参数
koaRouter.param('userName', (id, ctx, next) => {
    
    
  console.log('404');
  return next();
})

koaRouter.get('loginGet', '/login', (ctx, next) => {
    
    
  const {
    
     userName, pwd } = ctx.query;
  if (userName === 'gaoli' && pwd === '987654') {
    
    
    ctx.response.body = util.succ({
    
    userName: 'gaoli', id: '3456'});
  }
  else {
    
    
    ctx.response.body = util.fail('111111', {
    
    code: '111111', msg: '用户名或者密码不正确!'});
  }
})

koaRouter.post('/login', (ctx, next) => {
    
    
  const {
    
     userName, pwd } = ctx.request.body;
  if (userName === 'gaoli' && pwd === '987654') {
    
    
    ctx.response.body = util.succ({
    
    userName: 'gaoli', id: '3456'});
  }
  else {
    
    
    ctx.response.body = util.fail('111111', {
    
    code: '111111', msg: '用户名或者密码不正确!'});
  }
})

// 路由参数请求
koaRouter.get('loginPost', '/login/:userName/:pwd', ctx => {
    
    
  const {
    
     userName, pwd } = ctx.params;
  if (userName === 'gaoli' && pwd === '987654') {
    
    
    ctx.response.body = util.succ({
    
    userName: 'gaoli', id: '3456'});
  }
  else {
    
    
    ctx.response.body = util.fail('111111', {
    
    code: '111111', msg: '用户名或者密码不正确!'});
  }
})

// 命名路由
koaRouter.get('register', '/register/:flag', ctx => {
    
    
  if (flag === true) {
    
    
    ctx.body = util.succ({
    
    pageId: 'register.html'});
  }
  else {
    
    
    const path = koaRouter.url('loginPost', {
    
    userName: 'gaoli', pwd: '987654'});
    // 重定向到path,只能是get请求
    ctx.redirect(path);
  }
})
// 解决跨域问题
app.use(koaCors());
// 处理请求参数
app.use(koaBody());
app.use(koaRouter.routes());
app.use(koaRouter.allowedMethods())

// 启动服务器,监听端口
const {
    
     port, baseUrl } = defaultOption;
app.listen(port, () => {
    
    
  console.info(
    '\n服务器已启动 =>',
    cyan(`http://127.0.0.1:${
      
      port}${
      
      baseUrl}`)
  )
})

API

const KoaRouter = require('koa-router');

1. Router

Create a router instance.

let Router = new KoaRouter([opt]);
let router = new KoaRouter({
    
    
	prefix: '/web'
});
// url: /web/login
router.get('/login', (ctx, next) => {
    
    })
param type description
opt Object
opt.prefix String routing prefix

1.1 router.prefix();

Set route prefix.

router.prefix('/web');

2. get|post|put|patch|delete|del

router[method]([routeName,] url, [middleware], callback);
param type description
routeName String Route name, the presence of this parameter indicates a named route
url String routing
middleware Function middleware
callback Function Callback

2.1 Common Routing

router
  .get('/', (ctx, next) => {
    
    
    ctx.body = 'Hello World!';
  })
  .post('/users', (ctx, next) => {
    
    
    // ...
  })
  .put('/users/:id', (ctx, next) => {
    
    
    // ...
  })
  .del('/users/:id', (ctx, next) => {
    
    
    // ...
  })
  .all('/users/:id', (ctx, next) => {
    
    
    // ...
  });

2.2 Naming Routes

router.post('userInfo', '/getUserInfo/:id', ctx => {
    
    })

2.3 Using multiple middleware

router.get('/getUserInfo/:id', (ctx, next) => {
    
    
	console.log('middleware');
	next();
}, 
ctx => {
    
    
	console.log('callback');
})

3. router.url()

Generate complete path

const path = router.url(routeName, urlParams, [options]);
param type description
routeName String Route name, the presence of this parameter indicates a named route
urlParams String|Object routing parameters
options Object
options.query String|Object query parameters

3.1 Routing parameters

  1. When there is only one parameter in the route, the route parameter can be a string.
const path = router.url('userInfo', '1234');
  1. When there are multiple parameters in the route, use the object
const path = router.url('loginPost', {
    
    userName: 'gaoli', pwd: '987654'});

3.2 Query parameters

  1. object form
const path = router.url('loginGet', {
    
    }, {
    
    
	query: {
    
    
		userName: 'gaoli',
		pwd: '123456'
	}
});
  1. string form
const path = router.url('loginGet', {
    
    }, {
    
    
	query: 'userName=gaoli&pwd=123456'
});

4. router.redirect()

Redirect to the get interface.

router.redirect(source, destination, [code]);
param type description
source String route name or path
destination String route name or path
code Number http status code
router.redirect('/page/1', 'page/2');
router.redirect('userInfo', 'loginGet');

5. ctx.redirect()

ctx.redirect(destination, [code]);
router.get('userInfo', 'getUserInfo/:id', (ctx, next) => {
    
    
	ctx.redirect(loginGet);
})

5. router.route()

Find a route. Returns false if the route does not exist, and returns Layer (routing and interface information) if the route exists.

const layer = router.route(routeName);
param type description
routeName String route name

7. router.routes()

Returns a routing middleware that matches the request.

6. router.use()

Use middleware for matching routes. return route object

router.use([path], middleware)
param type description
path String|Array routing
middleware Function middleware
[…] Function middleware

6.1 Nested routes

var forums = new Router();
var posts = new Router();

posts.get('/', (ctx, next) => {
    
    ...});
posts.get('/:pid', (ctx, next) => {
    
    ...});
forums.use('/forums/:fid/posts', posts.routes(), posts.allowedMethods());

// responds to "/forums/123/posts" and "/forums/123/posts/123"
app.use(forums.routes());

7. router.param()

Run middleware for matching route parameters. Return router instance.

router.param(param, middleware)
param type description
param String route parameter name
middleware Function middleware
koaRouter.param('userName', (id, ctx, next) => {
    
    
  console.log('404');
  return next();
})

8. router.allowedMethods()

Returns a function in the middleware format.

router.allowedMethods([options])
param type description
options Object
options.trow Boolean Throws an error instead of setting status and headers
options.notImplemented Function Throw a return value to replace the default NotImplemented error
options.methodNotAllowed Function Throw return value to replace default MethodNotAllowed error

github-documentation

Guess you like

Origin blog.csdn.net/qq_36968599/article/details/119537245