鍍金池/ 問(wèn)答/Java  數(shù)據(jù)庫(kù)  HTML/ 加入cookies就報(bào)錯(cuò)了,加載不了頁(yè)面了?

加入cookies就報(bào)錯(cuò)了,加載不了頁(yè)面了?

前端的Ajax代碼:

/**
 * Created by Administrator on 2018/4/17.
 */

$(function() {

    var $loginBox = $('#loginBox');
    var $registerBox = $('#registerBox');
    var $userInfo = $('#userInfo');

    //切換到注冊(cè)面板
    $loginBox.find('a.colMint').on('click', function() {
        $registerBox.show();
        $loginBox.hide();
    });

    //切換到登錄面板
    $registerBox.find('a.colMint').on('click', function() {
        $loginBox.show();
        $registerBox.hide();
    });

    //注冊(cè)
    $registerBox.find('button').on('click', function() {
        //通過(guò)ajax提交請(qǐng)求
        $.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) {
                    //注冊(cè)成功
                    setTimeout(function() {
                        $loginBox.show();
                        $registerBox.hide();
                    }, 1000);
                }

            }
        });
    });

    //登錄
    $loginBox.find('button').on('click', function() {
        //通過(guò)ajax提交請(qǐng)求
        $.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.
 * 應(yīng)用程序的啟動(dòng)(入口)文件
 */
//加載express模塊
var express = require('express');
//加載模板處理模塊
var swig = require('swig');
//加載數(shù)據(jù)庫(kù)
var mongoose = require('mongoose');
//加載body-parser,用來(lái)處理post提交過(guò)來(lái)的數(shù)據(jù)
var bodyParser = require('body-parser');
//加載cookies模塊
var cookieParser = require('cookie-parser')
//創(chuàng)建app應(yīng)用=>NodeHS Http.createServer()
var app = express();

//設(shè)置靜態(tài)文件托管
//當(dāng)用戶訪問(wèn)的url以/public開(kāi)始,那么直接返回對(duì)應(yīng)__dirname + '/public'下的文件
app.use('/public', express.static(__dirname + '/public'));
// app.use('/static', express.static('public'));

//配置應(yīng)用模板
//定義當(dāng)前應(yīng)用所使用的模板引擎
//第一個(gè)參數(shù),模板引擎的名稱(chēng),同時(shí)也是模板文件的后綴,第二個(gè)參數(shù)表示用于解析處理模板內(nèi)容的方法
app.engine('html', swig.renderFile);
//設(shè)置模板文件存放的目錄,第一個(gè)參數(shù)必須是views,第二個(gè)參數(shù)是目錄
app.set('views', './views');
/*注冊(cè)所使用的模板引擎,第一個(gè)參數(shù)必須是view engine,第二個(gè)參數(shù)和app.engine這個(gè)方法中定義的模板引擎的名稱(chēng)(第一個(gè)參數(shù))是一致的*/
app.set('view engine', 'html');
//在開(kāi)發(fā)過(guò)程中,需要取消模板緩存
swig.setDefaults({cache: false});

//bodyparser設(shè)置
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'));

            //獲取當(dāng)前登錄用戶的類(lèi)型,是否是管理員
            User.findById(req.userInfo._id).then(function(userInfo) {
                req.userInfo.isAdmin = Boolean(userInfo.isAdmin);
                next();
            })
        }catch(e){
            next();
        }

    } else {
        next();
    }
} );

/*
 * 根據(jù)不同的功能劃分模塊
 * */
app.use('/admin', require('./routers/admin'));
app.use('/api', require('./routers/api'));
app.use('/', require('./routers/main'));

//監(jiān)聽(tīng)http請(qǐng)求
mongoose.connect('mongodb://localhost:27017/blog',function (err) {
    if(err){
        console.log('數(shù)據(jù)庫(kù)連接失敗');
    }else{
        console.log('數(shù)據(jù)庫(kù)連接成功');
        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');
//統(tǒng)一返回格式
var responseData;

router.use(function (req, res, next) {
    responseData = {
        code: 0,
        message:''
    }

    next();
});
/*
* 用戶注冊(cè)
* 注冊(cè)邏輯
*
* 1.用戶名不能為空
* 2.密碼不能為空
* 3.兩次輸入密碼必須一致
* 
* 1.用戶名是否已經(jīng)被注冊(cè)
*   數(shù)據(jù)庫(kù)查詢
* */
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;
    }


    //用戶名是否已經(jīng)被注冊(cè)了,如果數(shù)據(jù)庫(kù)中存在和我們要注冊(cè)的用戶名同名的數(shù)據(jù),表示改用戶名已經(jīng)被注冊(cè)了
    User.findOne({
        username: username
    }).then(function (userInfo) {
        if( userInfo){
            //表示數(shù)據(jù)庫(kù)中有改記錄
            responseData.code = 4;
            responseData.message = '用戶名已經(jīng)被注冊(cè)了'
            res.json(responseData);
            return;
        }
        //保存用戶注冊(cè)的信息到數(shù)據(jù)庫(kù)中
        var user = new User({
            username: username,
            password: password
        });
        return user.save();
    }).then(function (newUserInfo) {
        responseData.message = '注冊(cè)成功';
        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;
    }

    //查詢數(shù)據(jù)庫(kù)中相同用戶名和密碼的記錄是否存在,如果存在則登陸成功
    User.findOne({
        username: username,
        password: password
    }).then(function (userInfo) {
        if(!userInfo){
            responseData.code = 2;
            responseData.message = '用戶名或密碼錯(cuò)誤';
            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;

報(bào)錯(cuò)問(wèn)題:

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
回答
編輯回答
真難過(guò)

路由必須寫(xiě)在app.use(cookieparser());
之后才能通過(guò)cookie-parser中間件拿到cookie;

var express      = require('express')
var cookieParser = require('cookie-parser')
 
var app = express()
app.use(cookieParser())
2018年9月3日 22:32