返回列表

NodeJS操作cookie(二)

默认分类 2016/05/04 20:04

用了cookieParser可以直接使用req.cookies读取,使用req.cookie写入(注意少个s)

'use strict';

var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();
var port = 80;

app.use(cookieParser());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());

app.get('/all', function (req, res, next) {
    console.log(req.url);

    var result = {
        cookies: req.cookies,
        params: req.params,
        query: req.query,
        body: req.body,
        test: true
    };

    console.log(result);

    res.send(result);
});

app.get('/set', function (req, res) {
    res.cookie('UserId', '100010', {
        maxAge: 1000 * 60 * 30,
        httpOnly: true,
        domain: '.ymatou.com' //设置domain 共享当前域下面登录状态
    });

    res.cookie('UserId2', '100010', {
        maxAge: 1000 * 60 * 30,
        httpOnly: true,
        domain: '.ymatou.com' //设置domain 共享当前域下面登录状态
    });

    res.send({
        StatusCode: 200,
        Msg: 'set'
    });
});

app.get('/get', function (req, res) {
    //var cookie = req.headers['cookie'];
    var cookies = req.cookies;
    console.log(cookies);

    res.send({
        StatusCode: 200,
        Msg: 'get ' + cookies
    });
});

app.get('/clear', function (req, res) {
    res.clearCookie('UserId', {
        domain: '.ymatou.com'
    });

    res.send({
        StatusCode: 200,
        Msg: 'clear'
    });
});

app.listen(port, function () {
    console.log('Example app listening at http://0.0.0.0:%s', port);
});