Express

skylarkjs定位是前端解决方案,本身并不包括后台实现逻辑,但由于其前端路由本身就是基于express的router的,所以在一些需要使用后台的开发场景中,我们可以很方便的对skylarkjs进行简单的扩展,从而引入后台功能。

第一步:构建server.js

skylarkjs的服务启动功能,集成在skylark-slax-nodeserver模块中,我们可以在server.js中对这一模块进行扩展,让skylarkjs支持后台功能。

'use strict';
const SlaxServer = require('skylark-slax-nodeserver'),
    path = require('path'),
    logger = require('morgan'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    session = require('express-session'),
    methodOverride = require('method-override'),
    chalk = require('chalk'),
    // 后台相关路由
    routes = require('./backend/routes/routes'); 

// 添加后台逻辑
SlaxServer.prototype.startBackend = function(callback) {
    let app = this._express;
    if (app) {
        app.use(logger('dev'));
        app.use(bodyParser.urlencoded({ extended: true }));
        app.use(bodyParser.json());
        app.use(cookieParser());
        app.use(methodOverride('X-HTTP-Method-Override'));
        app.use(session({ secret: 'supernova', saveUninitialized: true, resave: true }));

        // Session-persisted message middleware
        app.use(function(req, res, next) {
            let err = req.session.error,
                msg = req.session.notice,
                success = req.session.success;

            delete req.session.error;
            delete req.session.success;
            delete req.session.notice;

            if (err) res.locals.error = err;
            if (msg) res.locals.notice = msg;
            if (success) res.locals.success = success;

            next();
        });
        routes(app);
    }
}

// 构建服务
function serve(slaxApp, options) {
    options.slax = slaxApp;
    const server = new SlaxServer(options);

    server.start(function() {
        console.log(chalk.blue('*'), 'slax server successfully started.');
        console.log(chalk.blue('*'), 'Serving files at:', chalk.cyan('http://localhost:' + options.port));
        console.log(chalk.blue('*'), 'Press', chalk.yellow.bold('Ctrl+C'), 'to shutdown.');
        return server;
    });
    // 启动后台相关路由
    server.startBackend();
}

// 启动服务
serve("deploy/bedoer.slax", {
    port: process.env.PORT || 8087
});

第二步:更改启动脚本

skylarkjs app中默认是通过脚本sjs serve来启动服务,由于我们对启动脚本进行了相关扩展,所以我们需要在package.json中更改启动脚本。

{
  "scripts": {
    "serve": "node server.js" (原来为"sjs serve ./deploy/demo.slax")
  }
}

第三步:启动

启动脚本还是原来的:

npm run build; npm run deploy; npm run serve -- --port=8088