koa1

2018-10-15  本文已影响25人  冷小谦

1.使用Koa架设一个HTTP服务。

const Koa = require('koa');
const app = new Koa();
app.listen(3000);

访问127.0.0.1:3000,页面显示not found,因为服务器没有任何内容。


image.png

2.context对象
koa提供了context对象,表示一次对话的上下文(http请求,http回复)。可以通过这个对象来控制response。

const Koa = require("koa");
const app = new Koa();

const main = ctx => {
  ctx.response.body = "hello world";
};
app.use(main);
app.listen(30001);
image.png

ctx.response和ctx.request。

3.http response类型
koa默认返回text/plain,如果想返回其他类型的内容,先用ctx.request.accepts判断客户端希望接入什么数据(http request的Accept字段),然后使用ctx.response.type指定返回数据。

ctx.request.accepts('html')请求的指定数据
const Koa = require("koa");
const app = new Koa();

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

4.网页模板
koa先读取模板文件,然后将模板返回给客户

const  fs = require('fs');

const main=ctx=>{
  ctx.response.type = 'html';
  ctx.response.body = fs.createReadStream('./demo/template.html');
}
template.html:
<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>koa</title>
  <meta name="description" content="koa Template">

</head>

<body>
  <h1>Hello Koa</h1>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读