本文出自从零到壹全栈部落javascript
(Node+Vue+微信公众号开发)企业级产品全栈开发速成周末班首期班(10.28号正式开班,欢迎抢座)css
第1步 - 环境安装java
请直接移步Node.js官网,以下图所示,直接点击最新版下载并进行安装。node
Node.js安装完毕后,打开终端,在终端分别输入以下命令,检测是否安装成功。git
Last login: Tue Jun 27 09:19:38 on console liyuechun:~ yuechunli$ node -v v8.1.3 liyuechun:~ yuechunli$ npm -v 5.0.3 liyuechun:~ yuechunli$
若是可以正确显示node和npm的版本,说明Node.js安装成功。程序员
第2步 - 安装Expressgithub
Last login: Mon Jul 10 11:14:16 on ttys001 liyuechun:~ yuechunli$ npm install -g express + express@4.15.3 added 42 packages in 7.337s liyuechun:~ yuechunli$
第3步 - 建立一个Express项目web
咱们准备使用Express
和Ejs
,这不是用来作CSS预处理的。咱们会手写一些CSS。咱们要用Ejs或者其它的模板引擎来处理Node和Express的数据。若是你会HTML的话,Ejs并不难。只要记住你须要集中精神,不然很容易出错。ajax
liyuechun:Desktop yuechunli$ pwd /Users/liyuechun/Desktop liyuechun:Desktop yuechunli$ mkdir 60MINUTES liyuechun:Desktop yuechunli$ cd 60MINUTES/ bogon:60MINUTES yuechunli$ express -e nodetest1 warning: option `--ejs' has been renamed to `--view=ejs' create : nodetest1 create : nodetest1/package.json create : nodetest1/app.js create : nodetest1/public create : nodetest1/views create : nodetest1/views/index.ejs create : nodetest1/views/error.ejs create : nodetest1/routes create : nodetest1/routes/index.js create : nodetest1/routes/users.js create : nodetest1/bin create : nodetest1/bin/www create : nodetest1/public/javascripts create : nodetest1/public/stylesheets create : nodetest1/public/stylesheets/style.css install dependencies: $ cd nodetest1 && npm install run the app: $ DEBUG=nodetest1:* npm start create : nodetest1/public/images bogon:60MINUTES yuechunli$
VSCode打开,项目结构以下:
第4步 - 编辑依赖项
好了,咱们如今有一些基本项目结构,可是还没完。你会注意到express的安装过程在你的nodetest1目录里建立了一个叫package.json
的文件,用文本编辑器打开这个文件,它应该是长这样的:
{ "name": "nodetest1", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "body-parser": "~1.17.1", "cookie-parser": "~1.4.3", "debug": "~2.6.3", "ejs": "~2.5.6", "express": "~4.15.2", "morgan": "~1.8.1", "serve-favicon": "~2.4.2" } }
这是一个标准的JSON格式文件,代表了咱们应用的依赖。咱们须要添加一点东西。好比对mongodb和Monk的调用。把dependencies部分改为这样:
{ "name": "nodetest1", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { "body-parser": "~1.17.1", "cookie-parser": "~1.4.3", "debug": "~2.6.3", "ejs": "~2.5.6", "express": "~4.15.2", "morgan": "~1.8.1", "serve-favicon": "~2.4.2", "mongodb": "*", "monk": "*" } }
第5步 – 安装依赖
如今咱们定义好了项目的依赖项。*号会告诉NPM“安装最新版本”。回到命令行窗口,进入nodetest1目录,输入:
bogon:nodetest1 yuechunli$ ls app.js package.json routes bin public views bogon:nodetest1 yuechunli$ npm install npm notice created a lockfile as package-lock.json. You should commit this file. added 80 packages in 4.563s bogon:nodetest1 yuechunli$ npm start > nodetest1@0.0.0 start /Users/liyuechun/Desktop/60MINUTES/nodetest1 > node ./bin/www Express server listening on port 3000... GET / 200 13.288 ms - 207 GET /stylesheets/style.css 200 3.295 ms - 111 GET /favicon.ico 404 1.757 ms - 1136
浏览器输入http://127.0.0.1:3000
,效果图以下:
查阅app.js
源码
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var index = require('./routes/index'); var users = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // uncomment after placing your favicon in /public app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', index); app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); console.log("Express server listening on port 3000..."); module.exports = app;
app.js
中添加代码
如今,咱们写点有用的。咱们不会直接在咱们的index页面里写“Hello World!”,咱们借这个机会学习一下如何使用route路由,同时学习一下Ejs引擎是如何工做的。在上面的app.js文件中添加以下
两行代码:
建立helloworld.js
文件
内容以下:
var express = require('express'); var router = express.Router(); /* GET HelloWorld page. */ router.get('/', function(req, res, next) { res.render('helloworld', { title: 'HelloWorld' }); }); module.exports = router;
建立helloworld.ejs
文件
内容以下:
<!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1><%= title %></h1> </body> </html>
运行程序npm start
启动服务器,而后在浏览器打开http://localhost:3000/helloworld
,应该能看到这个漂亮的界面了:
ejs⚠️去除
如上图所示,在VSCode中使用ejs
代码会出现语法不识别的问题,启动VSCode,经过快捷键⌘+P
快速打开窗口,将以下代码拷贝粘贴到里面,回车安装插件,而后重启便可。
ext install ejs-language-support
扫码申请加入全栈部落 |
---|
![]() |
第1步 - 更新HomeBrew
Last login: Wed Jul 12 09:27:06 on ttys000 liyuechun:~ yuechunli$ brew update Updated 1 tap (homebrew/core). ==> Updated Formulae radare2
第2步 – 安装Mongodb
liyuechun:~ yuechunli$ brew install mongodb ==> Downloading https://homebrew.bintray.com/bottles/mongodb-3.4.6.sierra.bottle Already downloaded: /Users/liyuechun/Library/Caches/Homebrew/mongodb-3.4.6.sierra.bottle.tar.gz ==> Pouring mongodb-3.4.6.sierra.bottle.tar.gz ==> Using the sandbox ==> Caveats To have launchd start mongodb now and restart at login: brew services start mongodb Or, if you don't want/need a background service you can just run: mongod --config /usr/local/etc/mongod.conf ==> Summary ? /usr/local/Cellar/mongodb/3.4.6: 18 files, 266.9MB
第3步 - 配置环境环境变量
liyuechun:~ yuechunli$ echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile
第4步 - 建立数据库路径
liyuechun:~ yuechunli$ mkdir -p /data/db
第5步 - 启动MongoDb(安装成功后命令行有提示)
liyuechun:~ yuechunli$ mongod --config /usr/local/etc/mongod.conf
第6步 - 链接到mongo
Last login: Wed Jul 12 11:00:21 on ttys000 liyuechun:~ yuechunli$ mongo MongoDB shell version v3.4.6 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.4.6 > 1+1 2 >
第7步 - 浏览器访问http://127.0.0.1:27017/
第8步 - 建立数据库
use nodetest1
这个命令,只有咱们插入数据时,才会真正建立数据库。
Last login: Wed Jul 12 11:35:52 on ttys001 liyuechun:~ yuechunli$ mongo MongoDB shell version v3.4.6 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.4.6 > use nodetest1 switched to db nodetest1 >
第9步 - 添加一些数据
我最喜欢的MongoDB的特性就是它使用JSON做为数据结构,这就意味着咱们对此很是的熟悉。若是你不熟悉JSON,先去读点相关资料吧,这超出了本教程的范围。
咱们添加一些数据到collection中。在这个教程里,咱们只有一个简单的数据库,username和email两个字段。咱们的数据看起来是这个样子的:
{ "_id" : 1234, "username" : "liyuechun", "email" : "liyuechun@cldy.org" }
你能够建立你本身的_id字段的值,不过我以为最好仍是让mongo来作这件事。它会为每一条记录建立一个惟一的值。咱们看看它是怎么工做的。在mongo的窗口中,输入:
> db.usercollection.insert({"username" : "liyuechun", "email" : "liyuechun@cldy.org" }) WriteResult({ "nInserted" : 1 }) >
重要提示:db就是咱们上面建立的nodetest1
数据库,就是咱们的collection
,至关于一张数据表。注意咱们不须要提早建立这个collection
,它会在第一次使用的时候自动建立。好了,按下回车。
第10步 - 数据库查询
> db.usercollection.find().pretty() { "_id" : ObjectId("59659d8fbd3dbae3899471c2"), "username" : "liyuechun", "email" : "liyuechun@cldy.org" } >
固然,你获得ObjectID应该是不同的,mongo会自动生成一个。若是你之前使用过JSON接口的服务,如今是否是会以为,哇,在web里调用这个应该很简单吧!嗯,你说对了。
提示:做为正式服务,你应该不但愿全部的数据都存在最顶层。关于mongodb数据结构的设计,多看看Google吧。
如今咱们有了一条数据,咱们多添加点吧。
> db.usercollection.insert( [ {"username":"yanan","email":"yanan@cldy.org"}, {"username":"fujinliang","email":"fujinliang@cldy.org"}, {"username":"shenpingping","email":"shenpingping@cldy.org"} ]) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) > db.usercollection.find().pretty() { "_id" : ObjectId("59659d8fbd3dbae3899471c2"), "username" : "liyuechun", "email" : "liyuechun@cldy.org" } { "_id" : ObjectId("59659ffebd3dbae3899471c3"), "username" : "yanan", "email" : "yanan@cldy.org" } { "_id" : ObjectId("59659ffebd3dbae3899471c4"), "username" : "fujinliang", "email" : "fujinliang@cldy.org" } { "_id" : ObjectId("59659ffebd3dbae3899471c5"), "username" : "shenpingping", "email" : "shenpingping@cldy.org" } >
第11步 – 把mongo链接到node
如今咱们来创建一个页面,把数据库里的记录显示成一个漂亮的表格。这是咱们准备生成的HTML内容:
<ul> <li><a href="mailto:liyuechun@cldy.org">liyuechun</a></li> <li><a href="mailto:yanan@testdomain.com">yanan</a></li> <li><a href="mailto:fujinliang@testdomain.com">fujinliang</a></li> <li><a href="mailto:shenpingping@testdomain.com">shenpingping</a></li> </ul>
打开nodetest1
项目的app.js
,如今接着往下看:
var index = require('./routes/index'); var users = require('./routes/users'); var helloworld = require('./routes/helloworld');
下面添加一行:
var userlist = require('./routes/userlist');
继续,找到下面代码的位置:
app.use('/', index); app.use('/users', users); app.use('/helloworld', helloworld);
下面添加一行:
app.use('/userlist', userlist);
第12步 – 建立 userlist.js
路由和 userlist.ejs
视图文件
以下图所示:
userlist.js
内容以下:
var express = require('express'); var router = express.Router(); /** * 这几行会告诉app咱们须要链接MongoDB,咱们用Monk来负责这个链接,咱们数据库位置是localhost:27017/nodetest1。注意27017是mongodb的默认端口,若是由于某些缘由你修改了端口,记录这里也要跟着改。 */ var mongo = require('mongodb'); var monk = require('monk'); var db = monk('127.0.0.1:27017/nodetest1'); /* GET userlist page. */ router.get('/', function (req, res, next) { var collection = db.get('usercollection'); collection.find({}, {}, function (e, docs) { res.render('userlist', {"userlist": docs}); }); }); module.exports = router;
userlist.ejs
内容以下:
<!DOCTYPE html> <html> <head> <title>USERLIST</title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1>Userlist</h1> <ul> <% for(var i in userlist){ %> <li> <a href="mailto:<%=userlist[i].email%>"> <%=userlist[i].username%> </a> </li> <% } %> </ul> </body> </html>
保存文件,重启node服务器。但愿你还记得怎么重启。打开浏览器,访问http://localhost:3000/userlist
,你应该能看到这样的界面:
如今你从数据库里取到了数据而且显示到了网页上。太棒了。
往数据库里写入数据也不是很困难。咱们须要一个route来接收POST请求而不是GET。咱们可使用Ajax,这是我最经常使用的方式。不过那可能须要另一篇教程了,因此这里咱们仍是用最原始的post手段。固然,要记住,若是你愿意,用ajax并不难。
第1步 – 创建你的数据输入页面
这里咱们须要快一点:创建两个丑陋的不加样式的文本框和一个提交按钮。像上面同样,咱们从app.use()
开始。打开app.js
找到下面的代码:
var index = require('./routes/index'); var users = require('./routes/users'); var helloworld = require('./routes/helloworld'); var userlist = require('./routes/userlist');
在下面加上:
var newuser = require('./routes/newuser');
再找到下面的代码:
app.use('/', index); app.use('/users', users); app.use('/helloworld', helloworld); app.use('/userlist', userlist);
在下面加上:
app.use('/newuser', newuser);
在routs
文件夹中建立newuser.js
文件,内容以下:
var express = require('express'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res, next) { res.render('newuser', { title: 'Add New User' }); }); module.exports = router;
在views
文件夹中建立newuser.ejs
文件,内容以下:
<!DOCTYPE html> <html> <head> <title>Add User</title> <link rel="stylesheet" href="/stylesheets/style.css" /> </head> <body> <h1> <%= title %> </h1> <form name="adduser" method="post" action="/adduser"> <input type="text" placeholder="username" name="username" /> <input type="text" placeholder="useremail" name="useremail" /> <input type="submit" value="submit" /> </form> </body> </html>
这里咱们建立一个form,method是post,action是adducer。简单明了。下面咱们定义了两个输入框和一个提交按钮。启动服务器,浏览器打开http://localhost:3000/newuser
效果图以下:
点提交按钮,会出现以下错误,咱们来修正错误。
Not Found 404 Error: Not Found at /Users/liyuechun/Desktop/60MINUTES/nodetest1/app.js:36:13 at Layer.handle [as handle_request] (/Users/liyuechun/Desktop/60MINUTES/nodetest1/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/Users/liyuechun/Desktop/60MINUTES/nodetest1/node_modules/express/lib/router/index.js:317:13) at /Users/liyuechun/Desktop/60MINUTES/nodetest1/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/Users/liyuechun/Desktop/60MINUTES/nodetest1/node_modules/express/lib/router/index.js:335:12) at next (/Users/liyuechun/Desktop/60MINUTES/nodetest1/node_modules/express/lib/router/index.js:275:10) at /Users/liyuechun/Desktop/60MINUTES/nodetest1/node_modules/express/lib/router/index.js:635:15 at next (/Users/liyuechun/Desktop/60MINUTES/nodetest1/node_modules/express/lib/router/index.js:260:14) at Function.handle (/Users/liyuechun/Desktop/60MINUTES/nodetest1/node_modules/express/lib/router/index.js:174:3) at router (/Users/liyuechun/Desktop/60MINUTES/nodetest1/node_modules/express/lib/router/index.js:47:12)
第2步 – 建立你的数据库处理函数
打开app.js
文件,找到下面的代码:
var index = require('./routes/index'); var users = require('./routes/users'); var helloworld = require('./routes/helloworld'); var userlist = require('./routes/userlist'); var newuser = require('./routes/newuser');
在下面添加一行:
var adduser = require('./routes/adduser');
再次找到下面的代码:
app.use('/', index); app.use('/users', users); app.use('/helloworld', helloworld); app.use('/userlist', userlist); app.use('/newuser', newuser);
在下面添加一行:
app.use('/adduser', adduser);
接下来在routes
文件夹下面建立adduser.js
文件,内容以下:
var express = require('express'); var router = express.Router(); // New Code var mongo = require('mongodb'); var monk = require('monk'); var db = monk('localhost:27017/nodetest1'); /* POST userlist page. */ router.post('/', function (req, res, next) { // Get our form values. These rely on the "name" attributes var userName = req.body.username; var userEmail = req.body.useremail; // Set our collection var collection = db.get('usercollection'); // Submit to the DB collection.insert({ "username": userName, "email": userEmail }, function (err, doc) { if (err) { // If it failed, return error res.send("There was a problem adding the information to the database."); } else { // If it worked, set the header so the address bar doesn't still say /adduser res.location("userlist"); // And forward to success page res.redirect("userlist"); } }); }); module.exports = router;
上面的代码是经过post请求拿到表单中的username
和email
,而后重定向到userlist
页面。
启动服务器,在浏览器中打开http://localhost:3000/newuser
,效果以下所示:
在里面输入用户名和邮箱,就会跳转到userlist
页面,以下面所示:
如今咱们正式的完成了使用Node.js,Exress,Ejs读取和写入Mongodb数据库,咱们已是牛X的程序员了。
恭喜你,真的。若是你认真的看完了这篇教程,而且很认真的学习而不仅是复制代码,你应该对routes, views,读数据,写入数据有了完整的概念。这是你用来开发任何其它完整的Web网站所须要的一切知识点!无论你怎么想,我以为这真挺酷的。
社群品牌:从零到壹全栈部落
定位:寻找共好,共同窗习,持续输出全栈技术社群
业界荣誉:IT界的逻辑思惟
文化:输出是最好的学习方式
官方公众号:全栈部落
社群发起人:春哥(从零到壹创始人,交流微信:liyc1215)
技术交流社区:全栈部落BBS
全栈部落完整系列教程:全栈部落完整电子书学习笔记
关注全栈部落官方公众号,每晚十点接收系列原创技术推送 |
---|
![]() |