CookieParserミドルウェアは、Webブラウザーから送信されたCookieのコンテンツを取得するために使用されます。 CookieParserミドルウェアを使用した後、
クライアントに代わって要求されたHTTO.IncomingMessageオブジェクトには、オブジェクトの配列であるCookies属性があります。
Webブラウザから送信されるすべてのCookieを保存し、各CookieはCookie属性値アレイのオブジェクトです。
index.htmlコード:
コードコピーは次のとおりです。
<!doctype html>
<html>
<head lang = "en">
<メタcharset = "utf-8">
<title>ファイルをサーバーにアップロード</title>
<script type = "text/javascript">
function submitcookie(){
var xhr = new xmlhttprequest();
xhr.open( "post"、 "index.html"、true);
document.cookie = "firstName = sisi";
document.cookie = "username = dr。";
xhr.onload = function(e){
if(this.status == 200)
document.getElementById( "res")。innerhtml = this.response;
};
xhr.send();
}
</script>
</head>
<body>
<h1> CookieParserミドルウェアの使用</h1>
<入力型= "button" value = "submit 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(req.cookiesのvarキー){
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( "聞き取り1337");
});
テスト結果