koa - 架设一个 HTTP 服务器

1,首先确保你安装了 node 环境

2,新建一个 webpack 项目,并安装 koa 模块

$ npm init
// 之后一直回车即可
$ npm install koa --save

3,新建一个 app.js,用来实现一个简单的 HTTP 服务

let Koa = require('koa')
let app = new Koa()
app.listen(3000)
console.log('server running at http://localtion:3000')

此时访问 localhost:3000,页面会显示 “Not Found”,这是因为我们并没有返回内容

4,Context 对象

Koa 提供了一个 Context 对象,表示一次对话的上下文(包括 HTTP 请求和 HTTP 回复)。通过加工这个对象,就可以控制返回给用户的内容。

const Koa = require('koa')
const app = new Koa()

const main = ctx => {
    // 发送给用户的内容
    ctx.response.body = 'Hello World'
}

app.use(main)
app.listen(3000)
console.log('server running at localhost:3000')

此时页面上会显示 “Hello World”

ctx.response 代表 HTTP Response。同样的 ctx.request 代表 HTTP Request

5,HTTP Response 的类型

Koa 默认返回的类型是 【text/plain】,如果想返回其他类型的内容,可以使用【ctx.request.accepts】判断,然后使用 【ctx.response.type】制定返回的内容。

【xml、html、json、text】

const main = ctx => {
    if(ctx.request.accepts('xml')){
        ctx.response.type = 'xml'
        ctx.response.body = '<data>Hello World</data>'
    } else if (ctx.request.accepts('html')) {
        ctx.response.type = 'html'
        ctx.response.body = '<p>Hello World</p>'
    } else if (ctx.request.accepts('json')) {
        ctx.response.type = 'json'
        ctx.response.body = { data: 'Hello World' }
    } else if (ctx.request.accets('text')) {
        ctx.response.type = 'text'
        ctx.response.body = 'Hello World'
    }
}

6,网页模板

实际开发中,返回给用户的网页往往都写成了模板文件。我们可以让 Koa 先读取模板文件,然后将这个模板返回给用户。

const fs = require('fs')

const main = ctx => {
    ctx.response.type = 'html'
    ctx.response.body = fs.createReadStream('./demo/template.html')
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值