002以太坊钱包开发-使用 koa 搭建钱包项目

引入 koa 及 web3.js

$ mkdir myWallet

$ cd myWallet

$ npm init

$ npm install web3

$ npm install koa

hello world

通过 vi index.js 新建文件,添加如下代码:

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

// response
app.use(ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);
console.log('server is starting at port 3000')

启动服务

$ node index.js

# 打印结果
server is starting at port 3000

访问 http://localhost:3000 ,效果如下:

Hello World

引入 koa-router

$ cd myWallet
$ npm install koa-router

新建 routers 目录,存放路由信息

$ mkdir routers
$ cd routers
$ vi index.js

添加如下的路由信息:

const router = require('koa-router')()

router.get('/', (ctx, next) => {
    ctx.body = 'Hello Router';
  });
module.exports = router

同时修改 myWallet/index.js的代码

const Koa = require('koa');
const routers = require('./routers/index')
const app = new Koa();

// 初始化路由中间件
app.use(routers.routes()).use(routers.allowedMethods())
app.listen(3000);
console.log('server is starting at port 3000')

启动项目

$ node index.js

通过访问 http://localhost:3000/ 查看运行结果:

Hello Router

获取请求数据

在koa中,获取GET请求数据源头是koa中request对象中的query方法或querystring方法。对于POST请求的处理,koa没有封装获取参数的方法,所以需要引用 koa-bodyparser 中间件。

$ cd myWallet
$ npm install koa-body --save

修改 myWallet/index.js的代码:

const Koa = require('koa');
const routers = require('./routers/index')
const koaBody = require('koa-body');

const app = new Koa();
// 引入 koa-body 中间件
app.use(koaBody({
  multipart: true
}));


// 初始化路由中间件
app.use(routers.routes()).use(routers.allowedMethods())
app.listen(3000);
console.log('server is starting at port 3000')

修改 routers/index.js 的代码:

const router = require('koa-router')()

router.get('/', (ctx) => {

  const body = ctx.request.query;

  ctx.body = 'Hello Router GET '+ JSON.stringify(body);
  });

router.post('/', (ctx) => {

    const body = ctx.request.body;

    ctx.body = 'Hello Router POST '+ JSON.stringify(body);
    });
module.exports = router

重启服务 node index.js,测试 GETPOST 请求:

# 测试 GET 请求
curl http://localhost:3000?a=1

# 运行结果
Hello Router GET {"a":"1"}

# 测试 POST 请求
curl -H "Content-Type:application/json" -X POST -d '{"aa": "11", "bb":"22"}' http://127.0.0.1:3000

# 运行结果
Hello Router POST {"aa":"11","bb":"22"}

源码地址

https://github.com/didianV5/web3EthWallet/tree/master/002_myWallet

关注公众号
关注公众号

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值