加入cookies就报错了,加载不了页面了?
前端的Ajax代码:
/**
* Created by Administrator on 2018/4/17.
*/
$(function() {
var $loginBox = $('#loginBox');
var $registerBox = $('#registerBox');
var $userInfo = $('#userInfo');
//切换到注册面板
$loginBox.find('a.colMint').on('click', function() {
$registerBox.show();
$loginBox.hide();
});
//切换到登录面板
$registerBox.find('a.colMint').on('click', function() {
$loginBox.show();
$registerBox.hide();
});
//注册
$registerBox.find('button').on('click', function() {
//通过ajax提交请求
$.ajax({
type: 'post',
url: '/api/user/register',
data: {
username: $registerBox.find('[name="username"]').val(),
password: $registerBox.find('[name="password"]').val(),
repassword: $registerBox.find('[name="repassword"]').val()
},
dataType: 'json',
success: function(result) {
$registerBox.find('.colWarning').html(result.message);
if (!result.code) {
//注册成功
setTimeout(function() {
$loginBox.show();
$registerBox.hide();
}, 1000);
}
}
});
});
//登录
$loginBox.find('button').on('click', function() {
//通过ajax提交请求
$.ajax({
type: 'post',
url: '/api/user/login',
data: {
username: $loginBox.find('[name="username"]').val(),
password: $loginBox.find('[name="password"]').val()
},
dataType: 'json',
success: function(result) {
$loginBox.find('.colWarning').html(result.message);
if (!result.code) {
//登录成功
setTimeout(function() {
window.location.reload();
}, 1000);
}
}
})
})
//退出
$('#logout').on('click', function() {
$.ajax({
url: '/api/user/logout',
success: function(result) {
if (!result.code) {
window.location.reload();
}
}
});
})
})
后端的app.js
/**
* Created by Administrator on 2018/4/16.
* 应用程序的启动(入口)文件
*/
//加载express模块
var express = require('express');
//加载模板处理模块
var swig = require('swig');
//加载数据库
var mongoose = require('mongoose');
//加载body-parser,用来处理post提交过来的数据
var bodyParser = require('body-parser');
//加载cookies模块
var cookieParser = require('cookie-parser')
//创建app应用=>NodeHS Http.createServer()
var app = express();
//设置静态文件托管
//当用户访问的url以/public开始,那么直接返回对应__dirname + '/public'下的文件
app.use('/public', express.static(__dirname + '/public'));
// app.use('/static', express.static('public'));
//配置应用模板
//定义当前应用所使用的模板引擎
//第一个参数,模板引擎的名称,同时也是模板文件的后缀,第二个参数表示用于解析处理模板内容的方法
app.engine('html', swig.renderFile);
//设置模板文件存放的目录,第一个参数必须是views,第二个参数是目录
app.set('views', './views');
/*注册所使用的模板引擎,第一个参数必须是view engine,第二个参数和app.engine这个方法中定义的模板引擎的名称(第一个参数)是一致的*/
app.set('view engine', 'html');
//在开发过程中,需要取消模板缓存
swig.setDefaults({cache: false});
//bodyparser设置
app.use( bodyParser.urlencoded({extended:true}) );
app.use( function(req, res, next) {
req.cookies = new cookieParser(req, res);
//解析登录用户的cookie信息
req.userInfo = {};
if (req.cookies.get('userInfo')) {
try {
req.userInfo = JSON.parse(req.cookies.get('userInfo'));
//获取当前登录用户的类型,是否是管理员
User.findById(req.userInfo._id).then(function(userInfo) {
req.userInfo.isAdmin = Boolean(userInfo.isAdmin);
next();
})
}catch(e){
next();
}
} else {
next();
}
} );
/*
* 根据不同的功能划分模块
* */
app.use('/admin', require('./routers/admin'));
app.use('/api', require('./routers/api'));
app.use('/', require('./routers/main'));
//监听http请求
mongoose.connect('mongodb://localhost:27017/blog',function (err) {
if(err){
console.log('数据库连接失败');
}else{
console.log('数据库连接成功');
app.listen(8081);
}
});
// app.listen(8081);
api.js
/**
* Created by Administrator on 2018/4/16.
*/
var express = require('express');
var router = express.Router();
var User = require('../models/User');
//统一返回格式
var responseData;
router.use(function (req, res, next) {
responseData = {
code: 0,
message:''
}
next();
});
/*
* 用户注册
* 注册逻辑
*
* 1.用户名不能为空
* 2.密码不能为空
* 3.两次输入密码必须一致
*
* 1.用户名是否已经被注册
* 数据库查询
* */
router.post('/user/register', function (req, res, next) {
var username = req.body.username;
var password = req.body.password;
var repassword = req.body.repassword;
//用户名是否为空
if(username == ''){
responseData.code = 1;
responseData.message = '用户名不能为空';
res.json(responseData);
return;
}
//密码不能为空
if(password == ''){
responseData.code = 2;
responseData.message = '密码不能为空';
res.json(responseData);
return;
}
// 两次输入的密码不一致
if(password != repassword){
responseData.code = 3;
responseData.message = '两次输入的密码不一致';
res.json(responseData);
return;
}
//用户名是否已经被注册了,如果数据库中存在和我们要注册的用户名同名的数据,表示改用户名已经被注册了
User.findOne({
username: username
}).then(function (userInfo) {
if( userInfo){
//表示数据库中有改记录
responseData.code = 4;
responseData.message = '用户名已经被注册了'
res.json(responseData);
return;
}
//保存用户注册的信息到数据库中
var user = new User({
username: username,
password: password
});
return user.save();
}).then(function (newUserInfo) {
responseData.message = '注册成功';
res.json(responseData);
});
});
router.post('/user/login', function (req, res, next) {
var username = req.body.username;
var password = req.body.password;
if( username == ''|| password ==''){
responseData.code = 1;
responseData.message = '用户名和密码不能为空';
res.json(responseData);
return;
}
//查询数据库中相同用户名和密码的记录是否存在,如果存在则登陆成功
User.findOne({
username: username,
password: password
}).then(function (userInfo) {
if(!userInfo){
responseData.code = 2;
responseData.message = '用户名或密码错误';
res.json(responseData);
return;
}
//用户名和密码是正确的
responseData.message = '登录成功';
responseData.userInfo = {
_id: userInfo._id,
username: userInfo.username
}
req.cookies.set('userInfo', JSON.stringify({
_id: userInfo._id,
username: userInfo.username
}));
res.json(responseData);
return;
})
});
/*
* 退出
* */
router.get('/user/logout', function(req, res) {
req.cookies.set('userInfo', null);
res.json(responseData);
});
module.exports = router;
报错问题:
TypeError: req.cookies.get is not a function
at D:\WorkSpace\WebStorm\project\app.js:42:21
at Layer.handle [as handle_request] (D:\WorkSpace\WebStorm\project\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\WorkSpace\WebStorm\project\node_modules\express\lib\router\index.js:317:13)
at D:\WorkSpace\WebStorm\project\node_modules\express\lib\router\index.js:284:7
at Function.process_params (D:\WorkSpace\WebStorm\project\node_modules\express\lib\router\index.js:335:12)
at next (D:\WorkSpace\WebStorm\project\node_modules\express\lib\router\index.js:275:10)
at urlencodedParser (D:\WorkSpace\WebStorm\project\node_modules\body-parser\lib\types\urlencoded.js:91:7)
at Layer.handle [as handle_request] (D:\WorkSpace\WebStorm\project\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\WorkSpace\WebStorm\project\node_modules\express\lib\router\index.js:317:13)
at D:\WorkSpace\WebStorm\project\node_modules\express\lib\router\index.js:284:7
at Function.process_params (D:\WorkSpace\WebStorm\project\node_modules\express\lib\router\index.js:335:12)
at next (D:\WorkSpace\WebStorm\project\node_modules\express\lib\router\index.js:275:10)
at expressInit (D:\WorkSpace\WebStorm\project\node_modules\express\lib\middleware\init.js:40:5)
at Layer.handle [as handle_request] (D:\WorkSpace\WebStorm\project\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\WorkSpace\WebStorm\project\node_modules\express\lib\router\index.js:317:13)
at D:\WorkSpace\WebStorm\project\node_modules\express\lib\router\index.js:284:7
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
路由必须写在app.use(cookieparser());
之后才能通过cookie-parser中间件拿到cookie;