Express middleware cookieParser details, middleware cookieparser
CookieParser middleware is used to obtain the content in cookies sent by web browsers. After cookieParser middleware is used,
The htto. IncomingMessage object requested by the client has a cookie attribute, which is an array of objects,
It stores all cookies sent by web browsers. Each cookie is an object in the array of cookies property values.
Index.html code:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head lang = "en">
<Meta charset = "UTF-8">
<Title> upload a file to the server </title>
<Script type = "text/javascript">
Function submitCookie (){
Var xhr = new XMLHttpRequest ();
Xhr. open ("post", "index.html", true );
Document. cookie = "firstName = Sisi ";
Document. cookie = "userName = Phd ";
Xhr. onload = function (e ){
If (this. status = 200)
Document. getElementById ("res"). innerHTML = this. response;
};
Xhr. send ();
}
</Script>
</Head>
<Body>
<H1> Use of cookieParser middleware <Input type = "button" value = "Submit cookie" onclick = "submitCookie ();"/>
<Div id = "res"> </div>
</Body>
</Html>
Server. js code:
Copy codeThe Code is as follows:
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 name:" + key );
Res. write (", cookie value:" + req. cookies [key] + "<br/> ");
}
Res. end ();
});
App. listen (1337, "127.0.0.1", function (){
Console. log ("Start listening 1337 ");
});
Test Results