使用 Koa2 可以快速的搭建一个简单的 Node 服务器
Hello Koa2
-
使用
npm init
创建package.json
-
安装 koa 依赖
npm install koa --save
-
根目录下新建
index.js
// index.js const Koa = require('koa'); const app = new Koa(); const port = 4001; app.use(async (ctx) => { ctx.body = 'Hello Koa2'; }); app.listen(port, () => { console.log('>>> Server Listen In: ' + port); });
-
浏览器访问 http://localhost:4001
搭建静态服务器
静态服务器可以根据 URL 直接返回静态文件,如前端 .html .js 等文件以及图片资源等
-
在根目录创建静态文件目录
/public/
-
安装 koa-static 依赖
npm install koa-static --save
-
index.js
中引入依赖并配置静态目录为/public/
,同时可以配置浏览器缓存时间// index.js // ... const static = require('koa-static'); app.use( static(path.join(`${__dirname}/public`), { maxage: 60000 }); )
路由
通过路由可以根据请求的不同 URL 触发不同的方法,以实现支持多个 api 接口
-
安装 koa-router 依赖
npm install koa-router --save
-
在根目录创建 routers 目录,并在目录下创建 index.js 文件
-
/routers/index.js
中引入依赖并配置// routers/index.js const router = require('koa-router')(); // 配置一个地址为 /api 的接口 router.get('/api', async ctx => { ctx.body = { status: 'success', data: { a: 1, } } }) module.exports = router;
-
入口文件引入路由配置并使用
// index.js // ... const router = require('./routers'); // ... // 通过中间件的方式使用,要注意跟其他中间件的先后关系 app.use(router.routes()); // ...
文件上传
实现了简单的文件上传的功能
// routers/index.js
const fs = require('fs');
const path = require('path');
// ...
// 文件上传的路由配置
router.post('/upload', async ctx => {
console.log('ctx.request.files', ctx.request.files.file.name);
// 获取上传文件,单个文件,若为多个文件,此处的 file 会变为数组
const file = ctx.request.files.file;
// 创建可读流
const reader = fs.createReadStream(file.path);
// 存放文件路径,相对于本目录
const filePath = `/upload/${file.name}`;
// 创建可写流
const writer = fs.createWriteStream(path.join(__dirname, `/public${filePath}`));
// 可读流通过管道写入可写流
reader.pipe(writer);
ctx.body = {
status: 'success',
path: filePath,
}
ctx.message = 'file very ok!';
})
// ...
Create-React-App 配置请求转发代理
前端 CRA 项目是没有带转发功能的,所以要自己手动配置
-
使用 http-proxy-middleware 插件做请求转发
npm install http-proxy-middleware --save
-
在
src/
目录下新建setupProxy.js
文件,在该文件中配置转发规则// src/setpuProxy.js const proxy = require('http-proxy-middleware'); module.exports = function (app) { // 接口代理 app.use( proxy.createProxyMiddleware('/api', { target: 'http://localhost:4001/', changeOrigin: true, }) ); // 上传代理 app.use( proxy.createProxyMiddleware('/upload', { target: 'http://localhost:4001/', changeOrigin: true, }) ); }