-
首先创建koaDemo文件夹,并进入koaDemo
-
npm init -y 生成package.json配置文件
-
npm install koa -S
注意:
npm install xxx -S (--save)
自动把包添加到dependencies
npm install xxx -D (--save-dev)
自动把包添加到devdependencies(开发环境) -
创建js文件
const Koa = require('koa'); const app = new Koa(); app.use(ctx => { ctx.body = 'Hello Koa'; }); app.listen(3000);
注意:这里使用require导入Koa,如果使用import,直接node运行会报错,还需要安装配置babel
-
运行js文件
node .\src\hello.js
-
这时浏览器访问 127.0.0.1:3000 就通了
为了使用es6的语法,我们安装babel,执行命令:
npm install -D babel-cli babel-preset-env
创建.babelrc文件
{
"presets": ["babel-preset-env"]
}
执行命令,运行程序
.\node_modules\.bin\babel-node .\src\hello.js
(不过就目前的情况来看,不装babel,import语法是用不了的,async貌似是可以)
npm i nodemon -D
然后在package.json中添加dev命令,这样每次src有改变,nodemon会自动帮我们重启项目
"scripts": {
"dev": "nodemon --watch src --exec babel-node src/index.js"
},
npm i @koa/router -S
注意路由的注册方式
app.use(indexRouter.routes())
.use(indexRouter.allowedMethods());
npm install koa-bodyparser -S
安装了koa-bodyparser后,可以直接用 ctx.request.body 访问请求体
首先创建一个错误处理中间件,放在中间件的最上方,以便捕获到所有错误,返回状态码500
支持 post 请求,需要传 canvas 参数,参数的接口如下表。
canvas: {
width: 375, // canvas 宽度
height: 812, // canvas 高度
temporarily: false, // 是否把图片上传到 cdn 。开发的时候使用。
resources: [
{
type: 'image', // 图片类型
attributes: {
url: 'src/resources/images/gamePaper/bg.png',
style: {
left: 0,
top: 0,
width: 375,
height: 812,
},
},
},
{
type: 'image',
attributes: {
url: 'http://tbfile.ixiaochuan.cn/img/png/id/670379726',
style: {
left: 65,
top: 448,
width: 246,
height: 125,
},
},
},
{
type: 'text', // 文字类型
attributes: {
content: '考号:01029378748',
style: {
left: 46,
top: 120,
fontSize: 14,
color: '#242529',
fontSize:30,
fontFamily: 'Impact'
},
},
},
],
}
- 完整的远程 url 。例如,http://tbfile.ixiaochuan.cn/img/png/id/670379726 。如果是项目的静态资源图片,需要强制使用 fileLoader (防止 urlLoader 生成 base64 dataURL)。
import xxxImg from 'file!../../images/xxx.png'
- 本项目本地图片文件,读取本地图片比远程图片更快。建议按照项目名放在 src/resources 目录下。例如,src/resources/images/gamePaper/bg.png
接口名 | method | 返回值 |
---|---|---|
/mergeimage | post | - temporarily 为 true , 临时(2分钟有效期)的图片 url 。否则,返回标识图片属性的结构(id / type 等)以及 合成的图片实体 |
查看临时图片,imageId 由调用 /mergeimage 接口生成
传参: { canvas: { fontSize: 17, fontFamily: 'serif', text: '你觉得我有多长', }, }
返回: {"ret":1,"data":{"width":119}}