1.创建一个koa的文件夹
# mkdir koa
2.进入koa文件夹目录
# cd koa
3.初始化 package.json
# npm init -y
这里的-y意思是省略创建过程中一直输yes的步骤
4.安装koa
# cnpm i koa --save
5.创建index.js
const Koa = require('koa');
const app = new Koa();
app.use( async(ctx) => {
ctx.body = "hello world"
});
app.listen(8080)
console.log("demo in run");
6.运行
node index.js
7.get请求
修改后的代码
const Koa = require('koa');
const app = new Koa();
const hostName = '127.0.0.1'; //IP
const port = 80; //端口
app.use(async ctx => {
const url = ctx.url;
const request = ctx.request;
const query = request.query; //或者可以直接用ctx.query
const querystring = request.querystring; //或者可以直接用ctx.querystring
ctx.body = {
url,
request,
query ,
querystring
};
});
app.listen(port, hostName, () => {
console.log(`服务运行在http://${hostName}:${port}`);
});
在浏览器输入http://127.0.0.1?test=helloword就可以看到接口返回的结果
8.post请求
安装koa-bodyparser中间件
默认请求Content-Type类型为application/x-www-form-urlencoded (用Postman工具要选这项)
cnpm i koa-bodyparser@3 --save
修改后的代码
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const hostName = '127.0.0.1'; //IP
const port = 80; //端口
const app = new Koa();
app.use(bodyParser());
app.use(async ctx => {
const url = ctx.url;
const type = ctx.method;
if (url === '/' && type === 'GET') {
let html = `
<h2>Hello Hoa</h2>
<form method="POST" action="/">
<p>姓名:</p>
<input name="username">
<p>年龄:</p>
<input name="age">
<p>个人网址</p>
<input name="website">
<button type="submit">submit</button>
</form>
`;
ctx.body = html;
} else if (url === '/' && type === 'POST') {
let postData = ctx.request.body;
ctx.body = postData;
} else {
ctx.body = '<h2>404</h2>';
}
});
app.listen(port, hostName, () => {
console.log(`服务运行在http://${hostName}:${port}`);
});
console.log('成功启动');
在浏览器输入http://127.0.0.1,默认进入get请求展示表单,填写表单后提交会进入post请求,并且展示接收到的数据
文章参考:https://www.jianshu.com/p/b988ce30bac3
koajs使用教程:https://wohugb.gitbooks.io/koajs/content/index.html