开始使用

下面从零搭建一个hello的服务。

第一步 创建项目,安装依赖

$ take maty-hello # 创建项目目录并进入
$ npm init # 初始化一个工程
$ npm install maty --save # 安装maty并保存

maty-hello 目录名即项目名,可以改为你的实际项目名

第二步 建立默认的子目录结构和示例文件,如下

maty-hello
├── interceptors
│   └── index.js
├── routers
│   └── hello.js
├── views
│   └── hello.njk
├── node_modules
├── package.json
└── app.js

interceptors、routers、views是maty默认加载配置和文件的目录,可以通过配置修改。如果是用maty全新构建的项目,建议使用默认即可。

第三步 添加服务代码、路由配置、视图文件

  1. app.js中添加如下代码

    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);
    });
  2. routers/hello.js中添加如下配置

    hello.js
    module.exports = {
      '/hello, /hello/:name': {
        handle(data, ctx) {
          return {
            'type': 'world'
          };
        },
        view: 'hello'
      }
    };
  3. views/hello.njk中添加如下模板代码

    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 看看吧!

以上代码托管于 https://github.com/tofishes/maty-hello

Last updated