Cookie未定义错误

时间:2016-10-12 06:22:44

标签: javascript node.js cookies

我得到的Cookie没有定义'此代码中的错误。这段代码出了什么问题?请帮忙解决。

$('#save-dashboard').on('click', function (e) {
        var filtersNew = $("#graph-filters").val();
        if (!filtersNew) {
            alert('No Filters!');
        }
        if (cookie.enabled())
        {
            cookie.defaults.path = '/';
            var cookieFilters = cookie.get('cookie-filter-list');
            if (cookieFilters) {
                cookieFilters = cookieFilters + '#' + filtersNew;
                cookie.defaults.expires = 30;
                cookie.set('cookie-filter-list', cookieFilters);
                cookie.defaults.path = '/';
            }
        } else {
            cookie.defaults.expires = 30;
            cookie.set('filter-list', cookieFilters);
            cookie.defaults.path = '/';
        }
    });

我已设置app.use(express.cookieParser())

1 个答案:

答案 0 :(得分:0)

以下是您应该如何处理Cookie:

  1. 打开终端
  2. 浏览到您的应用文件夹
  3. $ npm install cookie-parser

    您必须在应用中导入cookieparser。

    var express = require('express');
    var cookieParser = require('cookie-parser');    
    var app = express();
    app.use(cookieParser());
    

    cookie-parser解析Cookie标头,并使用由Cookie名称键入的对象填充req.cookies

    要设置新Cookie,请在快递应用中定义新路线,例如

    app.get('/cookie',function(req, res){
         res.cookie(cookie_name , 'cookie_value').send('Cookie is set');
    });
    

    获取cookie;

    app.get('/', function(req, res) {
      console.log("Cookies :  ", req.cookies);
    });
    

    您可以在Cookie中设置到期时间

    res.cookie(name , 'value', {expire : new Date() + 9999});
    

    最后清除cookie

    app.get('/clearcookie', function(req,res){
         res.clearCookie('cookie_name');
         res.send('Cookie deleted');
    });