Javascript

node.js&express操作cookie

本文主要是介绍node.js&express操作cookie,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
const experss = require('express');
const path = require('path');
const cookieparser = require('cookie-parser');
const app = experss();
app.listen(3000, () => {
    console.log(`web服务器工作在3000端口`);
});
//使用第三方cookie-parser中间件来获取cookie:
app.use(cookieparser());
//设置/定义cookie: res.cookie('cookie名称',值[,选项]);
app.get('/setcookie', (req, res) => {
    //maxAge:用来设置cookie的有效时间,时间单位为毫秒
    res.cookie('TEL', 110, { maxAge: 9 * 1000 });
    res.cookie('xingming', 'zhagnsan');
    res.cookie('email', 'zhangsan@163.com');
    res.cookie('fenshu', [60, 90, 80]);
    res.send(`<script>alert('cookie设置成功');</script>`);
});
app.get('/mytest', (req, res) => {
    res.send(`获取cookie值:${JSON.stringify(req.cookies)}`);
});
//获取cookie:
app.get('/getcookie', (req, res) => {
    console.log(req.cookies);
    let { xingming = '', email = '' } = req.cookies;
    res.send(`获取cookie ${xingming}  ${email}`);
});
这篇关于node.js&express操作cookie的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!