Koa2使用教程

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值