docs
routing
Routing
zely.js automatically generates routes based on your file tree of pages.
filename | result(path) |
---|---|
/index.ts | / |
/hello.ts | /hello |
/foo/bar.ts | /foo/bar |
/user/[id].ts | /user/:id |
/user/[id]/about.ts | /user/:id/about |
/foo/[...bar] | /foo/:bar* |
For example, if there is a pages/hello/[id].ts
file like below:
pages/hello/[id].ts
import { GET } from 'zely';
export default [
GET((ctx) => {
ctx.send({ message: `Hello ${ctx.params.id}` });
}),
];
And then...
GET /hello/world
The response will be:
JSON
{ "message": "Hello world" }
#Method
If you export an array containing handlers by default, the page is automatically displayed according to the request method.
export default
import { GET, POST } from 'zely';
import type { PageHandler } from 'zely';
export default [
// simple usage
GET({ foo: 'bar' }),
// access to req and res
POST(ctx => ({
id: ctx.params.id;
})),
]
You can use another method:
Exports functions corresponding get
, post
, delete
etc (http verbs)
Typescript
// get
export function get(ctx) {}
// post
export function post(ctx) {}
// etc...
Note: see context guide
#Route Parameters
You can access the current page parameters by ctx.params
.
pages/user/[id].ts
import type { Context } from 'zely';
export function get(ctx: Context) {
ctx.send({ hello: ctx.params.id });
}
#404 page
Handle access to non-existent pages with _404
pages.
pages/_404.ts
export default (ctx) => {
ctx.status(404).send({ message: 'Page Not Found!', code: 404 });
};
#request and response
Zely Server is based on node:http
module.
request
reference: http.req
response
reference: http.res