app.js文件
var express = require(‘express’);
var fs = require(‘fs’);
var app = express.createServer();
app.use(express.bodyParser());
app.use(express.cookieParser());
fs.readFile('./home.html’, 'utf-8’, function (error, data) {
if (error) {
console.log('读取文件 home.html 失败。');
throw error;
} else {
app.get('/', function (request, response) {
response.send(data);
});
}
});
app.post('/’, function (request, response) {
if (request.cookies.name) {
response.send('cookie值:' + request.cookies.name);
} else {
var minute = 60;
response.cookie('name', request.body.name, {maxAge: minute});
response.send('cookie不存在!')
}
});
app.post('/clear’, function (request, response) {
response.clearCookie('name');
response.send('cookie已清除')
});
app.listen(3000);
console.log(‘服务开启!’);
home.html文件
<!doctype html><html>
<head>
<meta charset="utf-8" />
<title>useCookie</title>
</head>
<body>
<form action="/" method="post">
<input type="text" placeholder="用户名" name="name" />
<input type="submit" value="提交" />
</form>
<form action="/clear" method="post">
<input type="submit" value="clear" />
</form>
</body>
</html>