60.nodejs+koa+mongod 实现简单的页面增删改查
*安装最新版的nodejs(保证7.6以上)。
*安装mongodb(建议安装3.4.x,因为我安装3.6版本的时候老是会卡在80%左右)
这是一个mongodb的教程 http://www.cnblogs.com/huangxincheng/archive/2012/02/18/2356595.html
*下面的操作假设是已经安装好nodejs,和配置好mongodb,并且能够运行正常
1.创建项目koa-mongodb,并进入到当前项目目录

2.创建package.json
npm init
3.安装koa和koa-router
npm install koa --save
4.先来启动一个简单也服务并搭建一个简单的页面
在项目根目录下创建app.js,并在app.js内编辑如下代码
const Koa = require('koa'); const app = new Koa(); const home = ctx => { ctx.response.body = 'Hello World'; }; app.use(home); app.listen(3000);
使用node启动 app.js
node app.js

在浏览器中打开 localhost:3000,成功

加入页面路由 koa-router 以及页面的css文件,并用html文件替代字符串拼接
新增pages目录并且添加home.html

const Koa = require('koa'); const app = new Koa(); const fs = require('fs') const home = ctx => { ctx.response.type = 'html'; ctx.response.body = fs.createReadStream('./pages/home.html'); }; app.use(home); app.listen(3000);
重新启动 node app.js 打开localhost:3000 页面就会变成我们替换掉的home.html的内容

加入页面路由 koa-router
npm install koa-route --save
app.js修改如下
const Koa = require('koa'); const route = require('koa-route'); const app = new Koa(); const fs = require('fs') const home = async (ctx) => { ctx.response.type = 'html'; ctx.response.body = await fs.createReadStream('./pages/home.html'); }; const about = (ctx) => { ctx.response.type = 'html'; ctx.response.body = '<a href="/">To Home Page</a><h1>about</h1>'; }; app .use(route.get('/', home)) .use(route.get('/about', about)) app.listen(3000);
修改一下 home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Home Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<a href="/about"> To About Page</a>
<h1>home</h1>
</body>
</html>
重新启动 node app.js 打开http://localhost:3000,点击看看,这就你完成了一个简单的路由


待续...

浙公网安备 33010602011771号