svrx
  • Languages
  • svrx
  • svrx
    • SUMMARY
    • Contributing to svrx
    • Getting Started
    • Blog
      • Server-X: A Pluggable Platform For Local Frontend Development
    • Guide
      • API Reference
      • Option Reference
      • How To Use Routes
    • Plugins
      • How To Write A Plugin
      • How To Use Plugins
    • Practice
      • Integrations
      • Recipes
  • svrx
    • 概要
    • 贡献指南
    • 快速上手
    • Blog
      • Server-X:一款可能提升你十倍工作效率的工具
      • 使用 svrx 实现更优雅的接口 Mock
      • 说说 Server-X 的免安装插件机制
    • 进阶指南
      • API 索引
      • 参数列表
      • Routing 路由的使用
    • 插件体系
      • 如何写一个插件
      • 插件的使用
    • 项目实战
      • 结合主流脚手架使用
      • 特定场景使用
Powered by GitBook
On this page
  • Getting Started
  • Features
  • Syntax
  • Route
  • Route Methods
  • Route Matching
  • Action List
  • send
  • sendFile
  • json
  • redirect(target[, code])
  • header
  • rewrite
  • proxy(target[, options])
  • handle
  • Route API for Plugins
  • Examples

Was this helpful?

  1. svrx
  2. Guide

How To Use Routes

PreviousOption ReferenceNextPlugins

Last updated 3 years ago

Was this helpful?

Getting Started

You can try the following commands to start svrx routing quickly:

touch route.js # create empty routing file
svrx --route route.js 

In your route.js:

get('/blog').to.json({ title: 'svrx' });

Then open /blog, you'll see the json output {title: 'svrx'}.

Features

  • support hot reloading ( check it out by editing your route.js now)

  • easy writing, clear reading

  • support expanding through

Syntax

[method](selector).to.[action](payload)

For example:

post('/blog').to.proxy('http://music.163.com');

This rule can be translate into:

  • method: post

  • selector: /blog

  • action: proxy

  • payload: 'http://music.163.com'

'to' is just a preposition word here, which can be omitted

Route

Route Methods

⚠️ 'delete' is a reserved word of javascript, so you might use del() to create a DELETE method.

Route Matching

Common Rules

  • /svrx/:id: named parameters matching, default parameter rule is (\w+)

  • /svrx/:id(hello|world): named parameters matching with custom parameter matching rule

  • /svrx(.*): unnamed parameters matching

  • /\/svrx\/(.*)$/: use regexp directly for complicated routes

Parameters

  • named parameters like /:id, can be accessed through ctx.params.id

  • unnamed parameters like /(hello|world)/(.*).html, can be accessed through ctx.params[0] and ctx.params[1]

  • regexp like /\/svrx\/(.*)$/, can be accessed through ctx.params[i] in order

Parameters Mapping

get('/html/:path.(html|htm)').to.sendFile('./{path}.{0}')
  • /html/index.html will send ${root}/html/index.html

  • /html/home.htm will send ${root}/html/home.htm

Action List

send

Send response content.

get('/blog').to.send({ title: 'this is a blog' });

send is a syntactic sugar for ctx.body of koa. And there're some default behaviors for different payload types.

  • string

    • if started with <, like <html>, the Content-Type header will be set as text/html

    • if not, return text/plain

  • object or array or number or boolean ...

    • return json, the Content-Type will be application/json

sendFile

Send file content, and it will auto set the Content-Type header according to the file extension.

get('/index.html').to.sendFile('./index.html');
  • root path = serve.base || root

  • ⚠️support parameters mapping, for example:

    get('/file/:id.html').to.sendFile('./assets/{id}.html')

json

Send json response, despite the type of payload.

get('/blog').to.json({title: 'svrx'});

redirect(target[, code])

Server side redirecting.

  • target: target path

  • code: http code, default is 302

get('/blog').to.redirect('/user');

⚠️support parameters mapping, for example:

get('/blog/:path(.*)').to.redirect('/user/{path}')

header

Set response headers. header doesn't send any response content, so you can chain this action to other actions.

get('/blog')
  .to.header({ 'X-Engine': 'svrx' })
  .json({ code: 200 });

rewrite

Rewrite routes.

⚠️support parameters mapping

get('/old/rewrite:path(.*)').to.rewrite('/svrx/{path}')
get('/svrx(.*)').to.send('Hello svrx')

Both /old/1 and /svrx/1 will return Hello svrx.

rewrite doesn't send any response content, you can chain this action to other actions.

proxy(target[, options])

Proxy path to target server.

  • target: target server

    • changeOrigin

    • secure

    • pathRewrite

get('/api(.*)').to.proxy('http://mock.server.com/')
get('/test(.*)').to.proxy('http://mock.server.com/', {
  secure: false,
})
get('/test/:id').to.proxy('http://{id}.dynamic.server.com/')

handle

handle is a powerful action, it defines a middleware of koa, which means all actions above can be implemented by handle, but the cost is the reduction of code readability.

get('/hello-world').to.handle((ctx)=>{
  ctx.type = 'html'
  ctx.body = '<body>Hello World</body>'
});

Instead of using handle, it is recommended to use 'smaller' actions, you can customize your own actions using route api for plugins, see next section.

Route API for Plugins

You can create a new action in your own plugin. There's a router object in your hooks.onCreate, which has 3 methods inside:

  • action: register an action just like proxy, json, ...

  • load: load a routing file

  • route: define a router in scripts

Examples

get('/handle(.*)').to.handle((ctx) => { ctx.body = 'handle'; });
get('/blog(.*)').to.json({ code: 200 });
get('/code(.*)').to.send('code', 201);
get('/json(.*)').to.send({ json: true });
get('/text(.*)').to.send('haha');
get('/html(.*)').to.send('<html>haha</html>');
get('/rewrite:path(.*)').to.rewrite('/query{path}');
get('/redirect:path(.*)').to.redirect('localhost:9002/proxy{path}');
get('/api(.*)').to.proxy('http://mock.server.com/')
get('/test(.*)').to.proxy('http://mock.server.com/', {
  secure: false,
})
get('/test/:id').to.proxy('http://{id}.dynamic.server.com/')
get('/query(.*)').to.handle((ctx) => {
  ctx.body = ctx.query;
});
get('/header(.*)')
  .to.header({ 'X-From': 'svrx' })
  .json({ user: 'svrx' });
get('/user').to.json({ user: 'svrx' });

get('/sendFile/:path(.*)').to.sendFile('./{path}');

svrx route supports all the http methods defined by .

The match rule of svrx route is based on , which is also used by and .

The following is just some briefs of matching rules, please check for more detail.

In fact, except , most actions do not have the ability to access the koa context, so we need parameters mapping for some actions.

Take as an example:

You can use to write your own action.

options: same as

Please read for more information.

methods
path-to-regexp
express
koa
path-to-regexp doc
plugin
Action:handle
sendFile
Route API for Plugins
proxy.options
How To Write A Plugin