在vsc中使用存取cookie的方法,制作一个简单答题界面
时间: 2024-03-15 17:46:56 浏览: 18
好的,我可以帮你解答这个问题。
首先,我们需要安装一个名为 `cookie-parser` 的 Node.js 中间件,来帮助我们在 Express 应用程序中处理 cookie。你可以通过以下命令来安装:
```
npm install cookie-parser
```
接下来,我们可以使用以下代码在 Express 应用程序中启用 cookie-parser:
```javascript
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
```
现在我们已经可以处理 cookie 了。接下来是如何制作一个简单答题界面。
我们可以使用以下代码来定义一个简单的路由,当用户访问 `/quiz` 路径时,会显示一个包含两个问题的答题界面。用户回答完问题后,答案会保存在 cookie 中。
```javascript
app.get('/quiz', (req, res) => {
// 检查 cookie 中是否已经保存了答案
const answered = req.cookies.answered || [];
// 定义两个问题和答案
const questions = [
{
id: 1,
text: '2 + 2 = ?',
options: [
{ text: '3', value: false },
{ text: '4', value: true },
{ text: '5', value: false },
],
},
{
id: 2,
text: '5 - 3 = ?',
options: [
{ text: '2', value: true },
{ text: '3', value: false },
{ text: '4', value: false },
],
},
];
// 检查哪些问题已经回答过了
const unanswered = questions.filter(q => !answered.includes(q.id));
// 如果所有问题都已经回答过了,显示一个消息
if (unanswered.length === 0) {
res.send('你已经回答过所有问题了!');
return;
}
// 获取下一个需要回答的问题
const question = unanswered[0];
// 显示问题和选项
let html = `<p>${question.text}</p>`;
html += '<form method="post">';
for (const option of question.options) {
html += `<input type="radio" name="answer" value="${option.value}"> ${option.text}<br>`;
}
html += '<input type="submit" value="提交">';
html += '</form>';
res.send(html);
});
app.post('/quiz', (req, res) => {
// 获取用户提交的答案
const answer = req.body.answer;
// 检查 cookie 中是否已经保存了答案
const answered = req.cookies.answered || [];
// 将这个问题的 ID 添加到已回答列表中
const questionId = req.body.questionId;
answered.push(questionId);
// 将答案保存在 cookie 中
res.cookie('answered', answered);
// 重定向到下一个问题页面
res.redirect('/quiz');
});
```
以上代码使用了两个路由:
- `GET /quiz`:显示答题界面。
- `POST /quiz`:处理用户提交的答案,并将答案保存在 cookie 中。
现在你可以启动你的 Express 应用程序,并访问 `http://localhost:3000/quiz` 来查看结果了。