一、配置环境
1、WebStorm安装
下载地址:https://www.jetbrains.com/webstorm/
激活地址:http://idea.lanyus.com/
获得注册码,注册码激活前务必将“0.0.0.0 account.jetbrains.com”添加到hosts文件中
//gg 跳到文件第一行
//Shift + g 跳到文件最后一行
$ vim /etc/hosts
2、NodeJS安装
下载地址:https://nodejs.org/en/
安装完成后执行下面的命令,显示版本号,则安装成功
$ node -v
3、MongoDB安装
1、安装MongoDB
下载MongoDB:https://www.mongodb.com/download-center?jmp=nav#community
进入下载目录
$ cd ~/Downloads
解压文件
$ tar -zxvf mongodb-osx-ssl-x86_64-3.6.5.tgz
将解压完的文件移动到想要的目录
$ mv -n ~/Downloads/mongodb-osx-ssl-x86_64-3.6.5 ~/Applications/mongodb/
将MongoDB目录写入配置文件,在~./bashrc或~/.bash_profile中加入下面一行
$ vim ~./bash_profile
将下面一行加入配置文件中
export PATH=<mongodb-install-directory>/bin:$PATH
将<mongodb-install-directory>替换为MongoDB的安装目录
2、启动MongoDB
1、使用默认/data/db文件夹(需要有读写权限)
$ sudo mkdir -p /data/db
启动MongoDB
$ mongod
2、将指定文件夹作为数据文件夹
$ mongod --dbpath <path to data directory>
启动成功,在Terminal看到如下提示:
[initandlisten] waiting for connections on port 27017
另开一个Terminal窗口,启动客户端
$ mongo
在Terminal看到如下提示,启动成功
MongoDB shell version v3.6.4
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.4
Server has startup warnings:
2018-06-22T17:59:07.520+0800 I CONTROL [initandlisten]
2018-06-22T17:59:07.521+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2018-06-22T17:59:07.521+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2018-06-22T17:59:07.521+0800 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2018-06-22T17:59:07.521+0800 I CONTROL [initandlisten]
2018-06-22T17:59:07.521+0800 I CONTROL [initandlisten] ** WARNING: This server is bound to localhost.
2018-06-22T17:59:07.521+0800 I CONTROL [initandlisten] ** Remote systems will be unable to connect to this server.
2018-06-22T17:59:07.521+0800 I CONTROL [initandlisten] ** Start the server with --bind_ip <address> to specify which IP
2018-06-22T17:59:07.521+0800 I CONTROL [initandlisten] ** addresses it should serve responses from, or with --bind_ip_all to
2018-06-22T17:59:07.521+0800 I CONTROL [initandlisten] ** bind to all interfaces. If this behavior is desired, start the
2018-06-22T17:59:07.521+0800 I CONTROL [initandlisten] ** server with --bind_ip 127.0.0.1 to disable this warning.
2018-06-22T17:59:07.521+0800 I CONTROL [initandlisten]
2018-06-22T17:59:07.521+0800 I CONTROL [initandlisten]
2018-06-22T17:59:07.521+0800 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
>
通过浏览器访问http://127.0.0.1:27017/
It looks like you are trying to access MongoDB over HTTP on the native driver port.
参考文章
Mac OS X 用 MongoDB 安装包进行手工安装
Install MongoDB Community Edition on macOS
二、构建项目
1、快速构建项目
通过Express 应用生成器可以快速创建一个应用的骨架。
通过如下命令安装:
$ npm install express-generator -g
创建一个testapp项目
$ express testapp
$ cd testapp
$ npm install
$ DEBUG=testapp npm start
在浏览器中打开 http://localhost:3000/ 网址就可以看到这个应用了。
2、实现一个简单的登录注册功能
Mongoose
- MongoDB是一个对象数据库,是用来存储数据的;存储的数据格式为JSON。
- Mongoose是封装了MongoDB操作(增删改查等)的一个对象模型库,是用来操作这些数据的。
安装mongoose
$ npm install mongoose
在项目根目录下新建/models/index.js,testapp就是我们要连接的数据库。
var mongoose = require('mongoose');
var testDB = "mongodb://localhost:27017/testapp";
mongoose.connect(testDB, function (err) {
if (err) {
console.log('connect fail');
} else {
console.log('connect success');
}
});
module.exports = mongoose;
在models新建一个user.js,新建一个用户Schema。
var mongoose = require("./index");
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name: {type: String},
mobile: {type: String},
pwd: {type: String}
});
module.exports = mongoose.model('User', UserSchema);
在项目根目录下新建/api/user.js,实现注册和登录功能。当注册添加数据时如果users表已经存在,则会保存到表中,如果不存在,则会创建users表,然后再保存数据。
var User = require('../models/user');
module.exports.userReg = function (req, res, next) {
var mobile = req.body.mobile;
var regUser = new User({
mobile: req.body.mobile,
pwd: req.body.pwd,
name: req.body.name
});
regUser.save(function (err, content) {
if (err) {
return res.send({status: 0, msg: err || '注册失败'});
} else {
return res.send({status: 1, msg: "注册成功"});
}
})
};
module.exports.userLogin = function (req, res, next) {
var userMobile = req.body.mobile;
var userPwd = req.body.pwd;
User.findOne({mobile: userMobile}, function (err, content) {
if (err) {
return res.send({status: 0, msg: err || '登录失败'});
} else {
var pwd = content.pwd;
if (pwd === userPwd) {
var userData = {"user_id": content._id,
"name": content.name,
"mobile": content.mobile};
return res.send({status: 1, msg: "登录成功", data: userData});
} else {
return res.send({status: 1, msg: "登录失败,密码错误"});
}
}
});
};
在routes新建user.js。
var express = require('express');
var router = express.Router();
var User = require("../api/user");
router.post('/register', User.userReg);
router.post('/login', User.userLogin);
module.exports = router;
在app.js中新增router。
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var testRouter = require('./routes/user');
var app = express();
var server = app.listen(3000, function(){
var host = server.address().address;
var port = server.address().port;
console.log('example app listening at http://%s:%s', host,port);
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/user', testRouter);
启动数据库,然后运行当前项目。
通过访问http://localhost:3000/user/register进行注册;http://localhost:3000/user/login进行登录。
项目GitHub地址:https://github.com/hornet1990/node-test