Middleware cookieParser digunakan untuk mendapatkan isi cookie yang dikirim oleh browser web. Setelah menggunakan middleware cookieParser,
Objek HTTO.incomingMessage yang diminta atas nama klien memiliki atribut cookie, yang merupakan array objek.
Ini menyimpan semua cookie yang dikirim oleh browser web, dan setiap cookie adalah objek dalam array nilai atribut cookie.
Kode index.html:
Salinan kode adalah sebagai berikut:
<! Doctype html>
<Html>
<head lang = "en">
<meta charset = "UTF-8">
<title> Unggah file ke server </iteme>
<type skrip = "Teks/JavaScript">
fungsi submitcookie () {
var xhr = xmlhttpRequest baru ();
xhr.open ("post", "index.html", true);
document.cookie = "FirstName = Sisi";
document.cookie = "nama pengguna = dr.";
xhr.onload = function (e) {
if (this.status == 200)
document.geteLementById ("res"). innerHtml = this.response;
};
xhr.send ();
}
</script>
</head>
<body>
<h1> Penggunaan middleware cookieParser </h1>
<input type = "Tombol" value = "Kirim cookie" onclick = "SubmitCookie ();" />
<Div id = "res"> </div>
</body>
</html>
Kode server.js:
Salinan kode adalah sebagai berikut:
var express = membutuhkan ("Express");
var fs = membutuhkan ("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) {
untuk (tombol var di req.cookies) {
res.write ("Nama Cookie:"+Key);
res.write (", nilai cookie:"+req.cookies [key]+"<br />");
}
res.end ();
});
app.listen (1337, "127.0.0.1", function () {
Console.log ("Mulai Mendengarkan 1337");
});
Hasil tes