项目作者: eggjs

项目描述 :
router for eggjs, fork from koa-router with some additional features
高级语言: JavaScript
项目地址: git://github.com/eggjs/egg-router.git
创建时间: 2019-01-29T02:55:18Z
项目社区:https://github.com/eggjs/egg-router

开源协议:Other

下载


@eggjs/router

@eggjs/router"">NPM version
@eggjs/router"">NPM download
Node.js CI
Test coverage
@eggjs/router"">Known Vulnerabilities
Node.js Version
PRs Welcome
CodeRabbit Pull Request Reviews

Router core component for Egg.js.

This repository is a fork of koa-router. with some additional features.
And thanks for the great work of @alexmingoia and the original team.

API Reference

Router ⏏

Kind: Exported class

new Router([opts])

Create a new router.

Param Type Description
[opts] Object
[opts.prefix] String prefix router paths

Example
Basic usage:

  1. import Koa from '@eggjs/koa';
  2. import Router from '@eggjs/router';
  3. const app = new Koa();
  4. const router = new Router();
  5. router.get('/', async (ctx, next) => {
  6. // ctx.router available
  7. });
  8. app
  9. .use(router.routes())
  10. .use(router.allowedMethods());

router.get|put|post|patch|delete|del ⇒ Router

Create router.verb() methods, where verb is one of the HTTP verbs such
as router.get() or router.post().

Match URL patterns to callback functions or controller actions using router.verb(),
where verb is one of the HTTP verbs such as router.get() or router.post().

Additionaly, router.all() can be used to match against all methods.

  1. router
  2. .get('/', (ctx, next) => {
  3. ctx.body = 'Hello World!';
  4. })
  5. .post('/users', (ctx, next) => {
  6. // ...
  7. })
  8. .put('/users/:id', (ctx, next) => {
  9. // ...
  10. })
  11. .del('/users/:id', (ctx, next) => {
  12. // ...
  13. })
  14. .all('/users/:id', (ctx, next) => {
  15. // ...
  16. });

When a route is matched, its path is available at ctx.routePath and if named,
the name is available at ctx.routeName

Route paths will be translated to regular expressions using
path-to-regexp.

Query strings will not be considered when matching requests.

Named routes

Routes can optionally have names. This allows generation of URLs and easy
renaming of URLs during development.

  1. router.get('user', '/users/:id', (ctx, next) => {
  2. // ...
  3. });
  4. router.url('user', 3);
  5. // => "/users/3"

Multiple middleware

Multiple middleware may be given:

  1. router.get(
  2. '/users/:id',
  3. (ctx, next) => {
  4. return User.findOne(ctx.params.id).then(function(user) {
  5. ctx.user = user;
  6. next();
  7. });
  8. },
  9. ctx => {
  10. console.log(ctx.user);
  11. // => { id: 17, name: "Alex" }
  12. }
  13. );

Nested routers

Nesting routers is supported:

  1. const forums = new Router();
  2. const posts = new Router();
  3. posts.get('/', (ctx, next) => {...});
  4. posts.get('/:pid', (ctx, next) => {...});
  5. forums.use('/forums/:fid/posts', posts.routes(), posts.allowedMethods());
  6. // responds to "/forums/123/posts" and "/forums/123/posts/123"
  7. app.use(forums.routes());

Router prefixes

Route paths can be prefixed at the router level:

  1. const router = new Router({
  2. prefix: '/users'
  3. });
  4. router.get('/', ...); // responds to "/users"
  5. router.get('/:id', ...); // responds to "/users/:id"

URL parameters

Named route parameters are captured and added to ctx.params.

  1. router.get('/:category/:title', (ctx, next) => {
  2. console.log(ctx.params);
  3. // => { category: 'programming', title: 'how-to-node' }
  4. });

The path-to-regexp module is
used to convert paths to regular expressions.

Kind: instance property of Router

Param Type Description
path String
[middleware] function route middleware(s)
callback function route callback

router.routes ⇒ function

Returns router middleware which dispatches a route matching the request.

Kind: instance property of Router

router.use([path], middleware) ⇒ Router

Use given middleware.

Middleware run in the order they are defined by .use(). They are invoked
sequentially, requests start at the first middleware and work their way
“down” the middleware stack.

Kind: instance method of Router

Param Type
[path] String
middleware function
[…] function

Example

  1. // session middleware will run before authorize
  2. router
  3. .use(session())
  4. .use(authorize());
  5. // use middleware only with given path
  6. router.use('/users', userAuth());
  7. // or with an array of paths
  8. router.use(['/users', '/admin'], userAuth());
  9. app.use(router.routes());

router.prefix(prefix) ⇒ Router

Set the path prefix for a Router instance that was already initialized.

Kind: instance method of Router

Param Type
prefix String

Example

  1. router.prefix('/things/:thing_id')

router.allowedMethods([options]) ⇒ function

Returns separate middleware for responding to OPTIONS requests with
an Allow header containing the allowed methods, as well as responding
with 405 Method Not Allowed and 501 Not Implemented as appropriate.

Kind: instance method of Router

Param Type Description
[options] Object
[options.throw] Boolean throw error instead of setting status and header
[options.notImplemented] function throw the returned value in place of the default NotImplemented error
[options.methodNotAllowed] function throw the returned value in place of the default MethodNotAllowed error

Example

  1. import Koa from '@eggjs/koa';
  2. import Router from '@eggjs/router';
  3. const app = new Koa();
  4. const router = new Router();
  5. app.use(router.routes());
  6. app.use(router.allowedMethods());

Example with Boom

  1. import Koa from '@eggjs/koa';
  2. import Router from '@eggjs/router';
  3. import Boom from 'boom';
  4. const app = new Koa();
  5. const router = new Router();
  6. app.use(router.routes());
  7. app.use(router.allowedMethods({
  8. throw: true,
  9. notImplemented: () => new Boom.notImplemented(),
  10. methodNotAllowed: () => new Boom.methodNotAllowed()
  11. }));

router.redirect(source, destination, [code]) ⇒ Router

Redirect source to destination URL with optional 30x status code.

Both source and destination can be route names.

  1. router.redirect('/login', 'sign-in');

This is equivalent to:

  1. router.all('/login', ctx => {
  2. ctx.redirect('/sign-in');
  3. ctx.status = 301;
  4. });

Kind: instance method of Router

Param Type Description
source String URL or route name.
destination String URL or route name.
[code] Number HTTP status code (default: 301).

router.route(name) ⇒ Layer | false

Lookup route with given name.

Kind: instance method of Router

Param Type
name String

router.url(name, params, [options]) ⇒ String | Error

Generate URL for route. Takes a route name and map of named params.

Kind: instance method of Router

Param Type Description
name String route name
params Object url parameters
[options] Object options parameter
[options.query] Object String query options

Example

  1. router.get('user', '/users/:id', (ctx, next) => {
  2. // ...
  3. });
  4. router.url('user', 3);
  5. // => "/users/3"
  6. router.url('user', { id: 3 });
  7. // => "/users/3"
  8. router.use((ctx, next) => {
  9. // redirect to named route
  10. ctx.redirect(ctx.router.url('sign-in'));
  11. })
  12. router.url('user', { id: 3 }, { query: { limit: 1 } });
  13. // => "/users/3?limit=1"
  14. router.url('user', { id: 3 }, { query: "limit=1" });
  15. // => "/users/3?limit=1"

router.param(param, middleware) ⇒ Router

Run middleware for named route parameters. Useful for auto-loading or
validation.

Kind: instance method of Router

Param Type
param String
middleware function

Example

  1. router
  2. .param('user', (id, ctx, next) => {
  3. ctx.user = users[id];
  4. if (!ctx.user) return ctx.status = 404;
  5. return next();
  6. })
  7. .get('/users/:user', ctx => {
  8. ctx.body = ctx.user;
  9. })
  10. .get('/users/:user/friends', ctx => {
  11. return ctx.user.getFriends().then(function(friends) {
  12. ctx.body = friends;
  13. });
  14. })
  15. // /users/3 => {"id": 3, "name": "Alex"}
  16. // /users/3/friends => [{"id": 4, "name": "TJ"}]

Router.url(path, params [, options]) ⇒ String

Generate URL from url pattern and given params.

Kind: static method of Router

Param Type Description
path String url pattern
params Object url parameters
[options] Object options parameter
[options.query] Object String query options

Example

  1. const url = Router.url('/users/:id', {id: 1});
  2. // => "/users/1"
  3. const url = Router.url('/users/:id', {id: 1}, {query: { active: true }});
  4. // => "/users/1?active=true"

Tests

Run tests using npm test.

Breaking changes on v3

  • Drop generator function support
  • Drop Node.js < 18.19.0 support

License

MIT

Contributors

Contributors

Made with contributors-img.