webStorm 创建node-server 服务
- 通过file->New->prejoct ->如图
- 然后Create就可以了
也直接可以下载 因为webStorm创建太慢了https://download.csdn.net/download/weixin_44114415/11818736
- 启动
npm run start
默认端口为http://localhost:3000/
node
修改完代码自动重启
通过第三方包命定行工具:nodemmon
nodemon
是基于node.js
开发的第三方命令行工具
# 全局安装
npm install nodemon --global
运行
nodemon ./main.js
package.json
"start":"nodemon ./bin/www"
这样修改完代码自动编译
准许异步请求
//设置允许跨域请求
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*'); //访问控制允许来源:所有
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); //访问控制允许报头 X-Requested-With: xhr请求
res.header('Access-Control-Allow-Metheds', 'PUT, POST, GET, DELETE, OPTIONS'); //访问控制允许方法
res.header('X-Powered-By', 'nodejs'); //自定义头信息,表示服务端用nodejs
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});
安装mongoDB 数据库
[菜鸟教程](http://www.runoob.com/mongodb/mongodb-tutorial.htmll)
-
开启数据库服务
#cmd # mongoDb 默认使用 monogd 命令所在根目录下的 /data/db 作为自己的数据库目录 # 在第一次执行mongod命令之前需要 手动创建 /data/db mongod #指定路径 mongod --dbpath=F:\data\db
-
连接数据库
mongo
-
退出连接
exit
-
基本
cmd
命令show dbs
- 查看显示所有的数据库
db
- 查看当前操作的数据库
use ’数据库名称‘
- 切换到指定数据库(如果没有就新建)
show collections
- 显示操作当前数据库的集合
db.集合名称.find()
- 查看集合内容
在Node中操作MongoDB 数据
-
使用第三方
mongoose
来操作MongoDB数据库- 第三方包
mongoose
基于 MongoDB官方的mongodb
包 - 文档:https://mongoosejs.com/docs/connections.html
- 起步:
-
安装:
npm i mongoose --save
-
基本使用 01:
- 第三方包
var mongoose = require('mongoose');
// 连接 MongoDB 数据库
mongoose.connect('mongodb://localhost/test', { useMongoClient: true });
mongoose.Promise = global.Promise;
// 创建一个模型
// 就是在设计数据库
// MongoDB 是动态的,非常灵活,只需要在代码中设计你的数据库就可以了
// mongoose 这个包就可以让你的设计编写过程变的非常的简单
var Cat = mongoose.model('Cat', { name: String });
//for (var i = 0; i < 100; i++) {
// 实例化一个 Cat
var kitty = new Cat({ name: '喵喵' + i });
// 持久化保存 kitty 实例
kitty.save(function (err) {
if (err) {
console.log(err);
} else {
console.log('meow');
}
});
//}
基本使用02:设计文档结构 、约束集合内容
var mongoose = require('mongoose')
var Schema = mongoose.Schema
// 1. 连接数据库
// 指定连接的数据库不需要存在,当你插入第一条数据之后就会自动被创建出来
mongoose.connect('mongodb://localhost/itcast', { useMongoClient: true })
// 2. 设计文档结构(表结构)
// 字段名称就是表结构中的属性名称
// 约束的目的是为了保证数据的完整性,不要有脏数据
var userSchema = new Schema({
username: {
type: String, //数据类型
required: true // 必须有 ,不能为空
},
password: {
type: String,
required: true
},
email: {
type: String,
default:'257@qq.com' //默认值
},
gender:{
type: Number,
enum: [0,1] //多选 只能选择0或1
}
})
// 3. 将文档结构发布为模型
// mongoose.model 方法就是用来将一个架构发布为 model
// 第一个参数:传入一个大写名词单数字符串用来表示你的数据库名称
// mongoose 会自动将大写名词的字符串生成 小写复数 的集合名称
// 例如这里的 User 最终会变为 users 集合名称
// 第二个参数:架构 Schema
//
// 返回值:模型构造函数
var User = mongoose.model('User', userSchema)
// 4. 当我们有了模型构造函数之后,就可以使用这个构造函数对 users 集合中的数据为为所欲为了(增删改查)
增
var admin = new User({
username: 'zs',
password: '123456',
// email: 'admin@admin.com'
})
admin.save(function (err, ret) {
if (err) {
console.log('保存失败')
} else {
console.log('保存成功')
console.log(ret)
}
})
查
查询所有
User.find(function (err, ret) {
if (err) {
console.log('查询失败')
} else {
console.log(ret)
}
})
根据条件查询单个数据
User.findOne({
username: 'zs'
}, function (err, ret) {
if (err) {
console.log('查询失败')
} else {
console.log(ret)
}
})
根据id
查询单个数据
User.findById([id],[callback])
删
根据条件删除所有:
User.remove({
username: 'zs1'
},function (error,rte) {
if (error) {
console.log('删除失败')
} else {
console.log(rte)
}
} )
根据条件删除一个:
User.findOneAndRemove(conditions,[options],[callback])
根据id
删除一个:
User.findByIdAndRemove(id,[options],[callback])
改
根据条件更新所有:
User.update(conditions,doc,[options],[callback])
根据指定条件更新一个:
User.findOneAndUpdate(conditions,[updata],[options],[callback])
根据id
更新一个:
User.findByIdAndUpdate('5cb19423287071029435eede',{
password: '123789'
},function (error,rte) {
if (error) {
console.log('更新失败')
} else {
console.log(rte)
}
})
3.数据密码 MD5
安装:
npm install blueimp-md5 --save
使用:
var md5 = require('blueimp-md5')
// 对密码进行 md5 重复加密
body.password = md5(md5(body.password))
数据库操作模块
- 跟目录下新建db文件夹后新建
models.js
/*1. 连接数据库*/
// 1.1. 引入mongoose
const mongoose = require('mongoose')
// 1.2. 连接指定数据库(URL只有数据库是变化的) mongodb://localhost:27017/数据库名称
mongoose.connect('mongodb://localhost:27017/gzhipin_test2')
// 1.3. 获取连接对象
const conn = mongoose.connection
// 1.4. 绑定连接完成的监听(用来提示连接成功)
conn.on('connected', () => {
console.log('数据库连接成功!')
})
/*2. 定义出对应特定集合的Model并向外暴露*/
// 2.1. 字义Schema(描述文档结构)
const userSchema = mongoose.Schema({
username: {type: String, required: true}, // 用户名
password: {type: String, required: true}, // 密码
type: {type: String, required: true}, // 用户类型: dashen/laoban
header: {type: String}, // 头像名称
post: {type: String}, // 职位
info: {type: String}, // 个人或职位简介
company: {type: String}, // 公司名称
salary: {type: String} // 月薪
})
// 2.2. 定义Model(与集合对应, 可以操作集合)
const UserModel = mongoose.model('user', userSchema) // 集合为: users(表)
// 2.3. 向外暴露Model
exports.UserModel = UserModel
- index.js中就可以使用UserModel这个模块了
var express = require('express');
var router = express.Router();
//引入模块
const {UserModel} = require('../db/models.js')
const md5 = require("blueimp-md5")
// var me = require('../public/javascripts/me.js');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'server is run...' });
});
router.post('/register',function (req,res) {
const {username,password,type} = req.body;
UserModel.findOne({
username
},function (error,user) {
if (user) {
//已有用户
res.send({code:1,msg:"用户已存在!"})
} else {
//没有用户需要注册
new UserModel({
username,
type,
"password":md5(password)
}) .save(function (error,user) {
//设置cookie (kookie名称,名称值,持续时间 毫秒*分钟*小时*天)
res.cookie('userid', username, {maxAge: 1000*60*60*24*7})
res.send({code:0,msg:{"_id":user._id,username,type}})
})
}
})
})
router.post('/login',function (req,res) {
const {username,password} = req.body;
const filter = {password: 0,__v:0}
//查 询 时 过 滤 出 指 定 的 属 性
UserModel.findOne({username,"password":md5(password)},filter,function (error,user) {
if (!user) {
res.send({code:1,msg:'用户名或密码错误!'})
} else {
//设置cookie (kookie名称,名称值,持续时间 毫秒*分钟*小时*天)
res.cookie('userid', username, {maxAge: 1000*60*60*24*7})
res.send({code:0,data:{user}})//因为过滤了 此时user中没有password 和__v
}
})
})
module.exports = router;
前台配置封装ajax
对应前台目录下新建api文件目录
ajax.js
/*
能发送ajax请求的函数模块
函数的返回值是promise对象
*/
import axios from 'axios'
const baseUrl = ''
// const baseUrl = 'http://localhost:4000'
export default function ajax(url, data={}, type='GET') {
url = baseUrl + url
if(type==='GET') { // 发送GET请求
// 拼请求参数串
// data: {username: tom, password: 123}
// paramStr: username=tom&password=123
let paramStr = ''
Object.keys(data).forEach(key => {
paramStr += key + '=' + data[key] + '&'
})
if(paramStr) {
paramStr = paramStr.substring(0, paramStr.length-1)
}
// 使用axios发get请求
return axios.get(url + '?' + paramStr)
} else {// 发送POST请求
// 使用axios发post请求
return axios.post(url, data)
}
}
index.js
const ajax from "./ajax.js";
export const register = (user) => ajax("/register",user,"POST");
export const login = (user) => ajax('/login',user,"POSt");