Cheat Sheet速查表
跳转到主要内容

Camp 速查表

本文根据 Devhints / Camp 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2017-09-21。

Camp 是一个 Node.js Web 服务器框架。本指南针对 Camp v17.x。

入门

快速入门

app.js

const Camp = require('camp')
const camp = Camp.start({ port: 1234 })

Web/index.html

<!doctype html>
<body>Hello world!</body>

Camp 默认提供……中的文件 web/ 。

路由

句柄 /search?q=rainbows

camp.path('/search', (req, res) => {
  const q = res.query.q
  res.json({ results: ··· })
})

另可提供: camp.post, camp.get.

模板

const tpl = Camp.template('./templates/post.html')

camp.path('/blog/:post.html', (req, res) => {
  res.template({
    text: 'Hello world'
  }, tpl)
})

参见: 模板

未找到

camp.notFound('/*.lol', (req, res) => {
  res.file('/404.html')
})

参见: 向下贯穿(Fall through)

底层处理程序

camp.handle((req, res, next) => {
  res.setHeader('X-Hello', 'world')
  next()
})

参见: 处理程序 (Handlers)

模板

基础模板

const tpl = Camp.template('/templates/post.html')

camp.path('/blog/:post.html', (req, res) => {
  res.template({
    text: 'Hello world'
  }, tpl)
})

隐式模板

camp.path('blog.html')

使用 blog.html 作为模板。

参见: 模板

高级功能

WebSockets

camp.ws('/path', (socket) => { ··· })
camp.wsChannels[path]
camp.wsBroadcast('/path', (req, res) => {
})

抱歉,我目前还没完全弄明白这一点,建议您查看一下相关文档。

参见: WebSocket