express使用cookie

2021/9/11 23:08:35

本文主要是介绍express使用cookie,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

-

/**
 cookie-parser使用
 安装
 npm install cookie-parser
 使用:
 1、const cookieParser = require('cookie-parser')
 2、app.use(cookieParser())
 3、设置cookie
 res.cookie("name","zhangsan",{maxAge:900000,httpOnly:true})
 4、获取cookie
 req.cookies.name
 5、配置参数说明
 maxAge:number  单位ms  过期时间
 signed:Boolean 是否加密  如果开启加密,浏览器端就会看到一个加密串,并且无法修改,如果修改了,获取时会获取到false
 expries:Date  过期时间 设置cookie过期的日期 和maxAge作用一样
 httpOnly:Boolean 默认是false  如果设置为true 就只能在nodejs后台来访问,不能再前台的javascript中访问了
 path: String 默认不用配置  如果配置,就只能在指定路由(页面)可以访问
 domain: String 域名   可以让同域的二级域名共享cookie 比如aaa.itying.com bbb.itying.com 但不能是 qq.com
        res.cookie("username","zhangsan",{maxAge:1000 * 60 * 60,domain:".itying.com"});
 secure: Boolean 默认为false 代表在http协议生效  如果为true 在只在https协议生效


 cookie加密
  1、配置中间件的时候需要传入秘钥   传入一个字符串
  app.use(cookieParser("itying"))
  2、设置cookie时,需要开启加密
  res.cookie("username","zhangsan",{maxAge:1000 * 60 * 60,signed:true});
  3、获取加密cookie
  req.signedCookies
 */

const express = require("express");
const app = express();
const cookieParser = require('cookie-parser')


// 配置cookieParser中间件
app.use(cookieParser("itying"))

app.get("/",(req,res) => {
  // 设置cookie  key是username  value是张三  过期时间是1小时
  // res.cookie("username","zhangsan",{maxAge:1000 * 60 * 60,path:"/artical"});
  // cookie加密

  res.cookie("username","zhangsan",{maxAge:1000 * 60 * 60,signed:true});
  res.send("首页")

})

app.get("/artical",(req,res) => {
  // 获取cookie
  let username = req.cookies.username;
  res.send("新闻页面---"+username)

})

app.get("/user",(req,res) => {
  // 获取cookie
  let username = req.cookies.username;
  res.send("用户---"+username)

})

app.get("/product",(req,res) => {
  // 获取cookie
  let username = req.signedCookies.username;
  res.send("用户---"+username)

})

app.listen(3000)

 

 

-



这篇关于express使用cookie的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程