内容纲要

Nuxt.js 是 vue 的服务器端渲染,配合前端 UI 组件库能快速开发。

集成 Express

Nuxt 服务器端可以集成 Express 框架,既可以 render UI 组件也可以提供 REST API。

在 express render 前端组件之前拦截路由,提供 API 访问。

app.get('/test1', (req, res) => {
  res.send('Success!')
})

// Give nuxt middleware to express
app.use(nuxt.render)

也可以导入外部模块,挂接到路由上

import api from './api'
app.use('/api', api)
./server/index.js       # express 入口
./server/api/index.js   # api 路由入口
./server/api/create-xxx.js
./server/api/get-xxx.js
./server/api/edit-xxx.js
./server/api/delete-xxx.js
./server/api/service/xxxxxService.js

express 入口 ./server/index.js

import express from 'express'
import bodyParser from 'body-parser'
import {
  Nuxt,
  Builder
} from 'nuxt'
import * as Datastore from 'nedb-core'
import bcrypt from 'bcrypt'

const db = new Datastore({
  filename: 'server/db/user',
  autoload: true
})

import api from './api'

const app = express()
const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 3000

app.set('port', port)

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: true
}))

app.use('/api', api)

let config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')

const nuxt = new Nuxt(config)

if (config.dev) {
  const builder = new Builder(nuxt)
  builder.build()
}

app.use(nuxt.render)

app.listen(port, host)
console.log('Server listening on ' + host + ':' + port) // eslint-disable-line no-console

db
  .find({
      identifier: 1
    }, (error, user) => {
      if (!user) {
        const administrator = {
          identifier: 1,
          firstName: 'Alfarr',
          lastName: 'Ferdinand',
          password: bcrypt.hashSync('123456', bcrypt.genSaltSync(6))
        }

        db
          .insert(administrator, (error) => {
            if (error) throw new Error(error)
          })
        }
      })

api 路由入口 ./server/api/index.js

import { Router } from 'express'
import signIn from './sign-in'
import createArticle from './create-article'
import editArticle from './edit-article'
import getArticles from './get-articles'
import getArticle from './get-article'
import deleteArticle from './delete-article'

const router = Router()

router.use(signIn)
router.use(createArticle)
router.use(editArticle)
router.use(getArticles)
router.use(getArticle)
router.use(deleteArticle)

export default router

create-article.js

import {
  Router
} from 'express'
import * as Datastore from 'nedb-core'

const router = Router()

router.post('/administration/create', function(req, res, next) {
  let db = new Datastore({
    filename: __dirname + '/../db/article',
    autoload: true
  })

  let title = ''
  let text = ''
  let createdDate = new Date()

  db
    .insert({
      title,
      text,
      createdDate
    }, (error, article) => {
      db.persistence.compactDatafile()
      if (!error) return res.json(article)
    })
})

export default router

CryptographyService.js

import crypto from 'crypto'

export default {

  /**
   * @param decrypted
   */
  encrypt: (decrypted) => {
    let cipher = crypto.createCipher('aes-256-cbc', 'd6F3Efeq')
    let crypted = cipher.update(decrypted.toString(), 'utf8', 'hex')
    crypted += cipher.final('hex')

    return crypted
  },

  /**
   * @param encrypted
   */
  decrypt: (encrypted) => {
    let decipher = crypto.createDecipher('aes-256-cbc', 'd6F3Efeq')
    let decrypted = decipher.update(encrypted.toString(), 'hex', 'utf8')
    decrypted += decipher.final('utf8')

    return decrypted
  }
}

参考

发表评论

电子邮件地址不会被公开。 必填项已用*标注