服务器之家

服务器之家 > 正文

express的中间件cookieParser详解

时间:2021-05-03 21:56     来源/作者:node.js教程网

cookieParser中间件用于获取web浏览器发送的cookie中的内容.在使用了cookieParser中间件后,

代表客户端请求的htto.IncomingMessage对象就具有了一个cookies属性,该属性之为一个对象的数组,

其中存放了所有web浏览器发送的cookie,每一个cookie为cookies属性值数组中的一个对象.

index.html代码:

 

复制代码 代码如下:

 <!DOCTYPE html>
 <html>
 <head lang="en">
     <meta charset="UTF-8">
     <title>向服务器上传文件</title>
     <script type="text/javascript">
         function submitCookie(){
             var xhr=new XMLHttpRequest();
             xhr.open("post","index.html",true);
             document.cookie="firstName=思思";
             document.cookie="userName=博士";
             xhr.onload= function (e) {
                 if(this.status==200)
                     document.getElementById("res").innerHTML=this.response;
             };
             xhr.send();
         }
     </script>
 </head>
 <body>
 <h1>cookieParser中间件的使用</h1>
 <input type="button" value="提交cookie" onclick="submitCookie();" />
 <div id="res"></div>
 </body>
 </html>

 

server.js代码:

 

复制代码 代码如下:

 var express=require("express");
 var fs=require("fs");
 var app=express();
 app.use(express.cookieParser());
 app.get("/index.html", function (req,res) {
     res.sendfile(__dirname+"/index.html");
 });
 app.post("/index.html", function (req,res) {
     for(var key in  req.cookies){
         res.write("cookie名:"+key);
         res.write(",cookie值:"+req.cookies[key]+"<br />");
     }
     res.end();
 });
 app.listen(1337,"127.0.0.1", function () {
     console.log("开始监听1337");
 });

 

测试结果

express的中间件cookieParser详解

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
返回顶部