cross-env在多个系统可以设置环境变量,让项目代码在多个系统下可以运行,nodemon在开发环境支持热更新
{
"name": "bl-express",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "cross-env NODE_ENV=dev nodemon ./bin/www",
"prd": "cross-env NODE_ENV=production nodemon ./bin/www"
},
"dependencies": {
"connect-redis": "^3.4.0",
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"express-session": "^1.15.6",
"http-errors": "~1.6.2",
"jade": "~1.11.0",
"morgan": "~1.9.0",
"mysql": "^2.16.0",
"redis": "^2.8.0",
"xss": "^1.0.3"
},
"devDependencies": {
"cross-env": "^5.2.0",
"nodemon": "^1.18.9"
}
}
express框架提供了封装好的session框架引入就可以使用,安装redis和connect-redis两个依赖,最后打开redis客户端查看结果
conf/db.js
const env = process.env.NODE_ENV // 环境参数
// 配置
let MYSQL_CONF
let REDIS_CONF
if (env === 'dev') {
// mysql
MYSQL_CONF = {
host: 'localhost',
user: 'root',
password: '*******',
port: '&&&&',
database: 'nodeServer'
}
// redis
REDIS_CONF = {
port: %%%%,
host: '127.0.0.1'
}
}
if (env === 'production') {
// mysql
MYSQL_CONF = {
host: 'localhost',
user: 'root',
password: '******',
port: '****',
database: 'nodeServer'
}
// redis
REDIS_CONF = {
port: ****,
host: '127.0.0.1'
}
}
module.exports = {
MYSQL_CONF,
REDIS_CONF
}
==app.use返回一个中间件,链接RedisStore,session的store引用RedisStore==
db/redis.js
const redis = require('redis')
const { REDIS_CONF } = require('../conf/db.js')
// 创建客户端
const redisClient = redis.createClient(REDIS_CONF.port, REDIS_CONF.host)
redisClient.on('error', err => {
console.error(err)
})
module.exports = redisClient
app.js
var express = require('express');
const session = require('express-session')
// 引入的是个函数 应用redis
const RedisStore = require('connect-redis')(session)
const blogRouter = require('./routes/blog')
const userRouter = require('./routes/user')
var app = express();
// redis 的客户端
const redisClient = require('./db/redis')
const sessionStore = new RedisStore({
client: redisClient
})
app.use(session({
secret: 'WJiol#23123_',
cookie: {
// path: '/', // 默认配置 不写也可以
// httpOnly: true, // 默认配置
maxAge: 24 * 60 * 60 * 1000
},
store: sessionStore //将session存到redis中
}))