开始使用
下面从零搭建一个hello的服务。
第一步 创建项目,安装依赖
$ take maty-hello # 创建项目目录并进入
$ npm init # 初始化一个工程
$ npm install maty --save # 安装maty并保存
第二步 建立默认的子目录结构和示例文件,如下
maty-hello
├── interceptors
│ └── index.js
├── routers
│ └── hello.js
├── views
│ └── hello.njk
├── node_modules
├── package.json
└── app.js
interceptors、routers、views是maty默认加载配置和文件的目录,可以通过配置修改。如果是用maty全新构建的项目,建议使用默认即可。
第三步 添加服务代码、路由配置、视图文件
app.js中添加如下代码
const maty = require('maty'); const app = maty(); const port = 8080; app.listen(port, () => { const startInfo = `server run at http:\/\/localhost:${port}`; console.log(startInfo); });
routers/hello.js中添加如下配置
module.exports = { '/hello, /hello/:name': { handle(data, ctx) { return { 'type': 'world' }; }, view: 'hello' } };
views/hello.njk中添加如下模板代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hello page - maty.js</title> </head> <body> <h3>Hi, this is a hello page with maty.js</h3> {% if type %} <p>get type '{{ type }}' form `router.handle` method.</p> {% endif %} {% if ctx.param.name %} <p>get name '{{ ctx.param.name }}' form `ctx.param.name` with inner object ctx.</p> {% endif %} </body> </html>
最后,启动服务
$ node app.js
分别访问http://localhost:8080/hello http://localhost:8080/hello/maty 看看吧!
Last updated
Was this helpful?