koa1

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>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、基本用法 1.1 架设 HTTP 服务 // demos/01.jsconst Koa = require('...
    majun00阅读 1,426评论 0 5
  • 1.简书 koa是由Express原班人马打造,致力于成为一个更小、更富有表现力、更健壮的Web框架。使用koa编...
    不去解释阅读 2,714评论 0 11
  • Koa 必须使用 7.6 以上的版本。如果你的版本低于这个要求,就要先升级 Node。 基本用法 Koa 提供一个...
    Gukson666阅读 2,495评论 0 1
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,087评论 19 139
  • ——这是jerry(之前的CEO)写给我们的月总结中的一段话。很喜欢,就保存下来了。一直留在私人文集里面,但是这个...
    浩3108阅读 376评论 0 0