一、前言
本文是关于如何用nodejs搭建自己的网站,如果有自己的服务器,可以将项目部署到服务器上,绑定域名,就可以通过域名来访问了,我的作品展示这个网站就是基于nodejs搭建的http://works.lishuaishuai.com/
二、如何搭建
1) 安装nodejs,略。
2) 安装mongodb,略。
3)安装express框架
express官网:http://expressjs.com/
express中文网站:http://www.expressjs.com.cn/
a. 通过应用生成器工具 express
可以快速创建一个应用的骨架。
通过如下命令安装:
$ npm install express-generator -g
-h
选项可以列出所有可用的命令行选项:
$ express -h Usage: express [options] [dir] Options: -h, --help output usage information -V, --version output the version number -e, --ejs add ejs engine support (defaults to jade) --hbs add handlebars engine support -H, --hogan add hogan.js engine support -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css) --git add .gitignore -f, --force force on non-empty directory
例如,下面的示例就是在当前工作目录下创建一个命名为 myapp 的应用。
$ express myapp -e
注意:-e表示支持ejs模板引擎,默认是jaden。
然后安装所有依赖包:
$ cd myapp $ npm install
启动这个应用(MacOS 或 Linux 平台):
$ DEBUG=myapp npm start
Windows 平台使用如下命令:
> set DEBUG=myapp & npm start
然后在浏览器中打开 http://localhost:3000/
网址就可以看到这个应用了。
通过 Express 应用生成器创建的应用一般都有如下目录结构:
. ├── app.js ├── bin │ └── www ├── package.json ├── public │ ├── images │ ├── javascripts │ └── stylesheets │ └── style.css ├── routes │ ├── index.js │ └── users.js └── views ├── error.ejs ├── index.ejs └── layout.ejs 7 directories, 9 files
package.json
:是模块管理包,项目信息和模块的版本号。
app.js
:项目的启动文件,可以说是项目的核心。主要写一些公共的功能。
bin
:文件下有个无后缀的www文件,这是项目的入口文件,配置web服务端口和一些监听事件。
node_modules
:项目的依赖的的文件模块。
public
:项目的静态资源文件集,很容易看出图片、css文件、js文件都放在这里。
routes
:项目的路由模块,其中已经默认了index.js和user.js文件。在这里其实也包括一般后台语言中的控制器内容,当然在大的项目上是可以分离开来的。
views
:项目的模版文件,是ejs模版引擎,和html文件差不多。
b. 我们创建数据库:
创建一个集合,也就是关系型数据库中的表,插入一条数据
导入monogDB连接模块,express 官方介绍的是mongoskin模块,这里介绍通过mongoose安装。Mongoose是在node.js异步环境下对mongodb进行便捷操作的对象模型工具。
c. 安装mongoose
在myapp项目下执行命令 npm install mongoose -save
安装保存到node_modules,也可以在package.json中配置”mongoose”: “^4.4.12”
,然后命令npm install
安装。
在app.js文件中加入
var mongoose = require('mongoose');
d.构建代码
在myapp目录下创建models文件夹,并在内部创建user.js作为实体类映射数据库的users集合
var mongoose = require("mongoose"); // 顶会议用户组件 var Schema = mongoose.Schema; // 创建模型 var userScheMa = new Schema({ userid: String, password: String }); // 定义了一个新的模型,但是此模式还未和users集合有关联 exports.user = mongoose.model('users', userScheMa); // 与users集合关联
修改index.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/common.min.css' /> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1>Hello World</h1> <p>Welcome to <%= title %></p> <p><ahref="login">登陆</a></p> </body> </html>
创建login.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/common.min.css' /> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1>Hello World</h1> <p>Welcome to <%= title %></p> <form action="homepage" method="post"> <p> <span>userId:</span> <br> <input id="userid" name="userid" type="text"> </p> <p> <span>password:</span> <br> <input id="password" name="password" type="password"> </p> <p><input type="submit" value="submit"></p> </form> </body> </html>
创建logout.ejs
<!DOCTYPE html> <html lang="en"> <head> <metacharset="UTF-8"> <title><%= title %></title> <linkrel='stylesheet'href='/stylesheets/common.min.css' /> <linkrel='stylesheet'href='/stylesheets/style.css' /> </head> <body> <h1>Hello World</h1> <p>Welcome to <%= title %></p> <p>正在登出...</p> <scripttype="text/javascript"> setTimeout(function(){ window.location.href = "/"; }, 500); </script> </body> </html>
创建homepage.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/common.min.css' /> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1>Hello World</h1> <p>Welcome to <%= title %></p> <p><a href="logout">登出</a></p> </body> </html>
error.ejs 是出错页面,这里没有做。
在routes下的index.js配置路由,也就是请求映射处理
修改index.ejs
var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var user = require('../models/user').user; mongoose.connect('mongodb://localhost/myapp'); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title:'主页' }); }); /*login*/ router.get('/login', function(req, res) { res.render('login', { title: 'login' }); }); /*logout*/ router.get('/logout', function(req, res) { res.render('logout', { title: 'logout' }); }); /*hompage*/ router.post('/homepage', function(req, res) { var query_doc = {userid: req.body.userid, password: req.body.password}; (function(){ user.count(query_doc, function(err, doc){ if(doc == 1){ console.log(query_doc.userid + ": login success in " + new Date()); res.render('homepage', { title: 'homepage' }); }else{ console.log(query_doc.userid + ": login failed in " + new Date()); res.redirect('/'); } }); })(query_doc); }); module.exports = router;
这样,应用就能够跑起来了。在项目根目录通过命令启动
$ npm start
在浏览器中访问http://127.0.0.1:3000/
三、总结
将这个例子放在了github,可自行下载https://github.com/li-shuaishuai/myapp
这里面用到的lss.common.css是我在写网站的时候用到的css初始化文件,发布在了npm上在使用的时候可以通过命令安装:
$ npm install lss.common.css
哇……