Middleware Cookieparser ใช้เพื่อรับเนื้อหาของคุกกี้ที่ส่งโดยเว็บเบราว์เซอร์ หลังจากใช้มิดเดิลแวร์ Cookieparser แล้ว
วัตถุ HTTO.InmingMessage ที่ร้องขอในนามของลูกค้ามีแอตทริบิวต์คุกกี้ซึ่งเป็นอาร์เรย์ของวัตถุ
มันเก็บคุกกี้ทั้งหมดที่ส่งโดยเว็บเบราว์เซอร์และคุกกี้แต่ละตัวเป็นวัตถุในอาร์เรย์ค่าแอตทริบิวต์ของคุกกี้
index.html รหัส:
การคัดลอกรหัสมีดังนี้:
<! doctype html>
<html>
<head lang = "en">
<meta charset = "utf-8">
<title> อัปโหลดไฟล์ไปยังเซิร์ฟเวอร์ </title>
<script type = "text/javascript">
ฟังก์ชั่น submentcookie () {
var xhr = ใหม่ xmlhttprequest ();
xhr.open ("โพสต์", "index.html", จริง);
document.cookie = "firstName = sisi";
document.cookie = "ชื่อผู้ใช้ = dr.";
xhr.onload = function (e) {
if (this.status == 200)
document.getElementById ("res"). innerhtml = this.response;
-
xhr.send ();
-
</script>
</head>
<body>
<H1> การใช้ Middleware CookieParser </h1>
<อินพุต type = "ปุ่ม" value = "ส่งคุกกี้" onclick = "submentcookie ();" -
<div id = "res"> </div>
</body>
</html>
Server.js รหัส:
การคัดลอกรหัสมีดังนี้:
var express = ต้องการ ("express");
var fs = ต้องการ ("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) {
สำหรับ (คีย์ var ใน req.cookies) {
res.write ("ชื่อคุกกี้:"+คีย์);
res.write (", ค่าคุกกี้:"+req.cookies [key]+"<br />");
-
res.end ();
-
app.listen (1337, "127.0.0.1", function () {
console.log ("เริ่มฟัง 1337");
-
ผลการทดสอบ