javascript - 无法在请求 NodeJS 中访问自定义值
问题描述
我试图在我的请求中存储一些随机值。像这样:
req.name = "Mark"
问题是我只能在我设置的控制器中访问它。当我
console.log(req.name)
在另一个控制器中我得到未定义。
我的代码在这里:
export const getCaptcha = async (req, res, next) => {
const captcha = await svgCaptcha.createMathExpr({
size: 5,
noise: 3,
color: true,
background: '#08af96'
})
req.captcha = captcha.text
res.status(200).send(captcha.data)
}
export const checkCaptcha = (req, res, next) => {
const { result } = req.body
console.log(req.captcha)
// if (result !== req.captcha) {
// throw new Error('Invalid captcha!')
// }
// res.status(200).json({
// message: 'Success'
// })
}
路由组件:
import express from 'express'
import { getCaptcha, checkCaptcha } from '../controllers/captcha'
const router = express.Router()
router.get('/captcha', getCaptcha)
router.post('/captcha', checkCaptcha)
export default router
应用程序.js
import captchaRoutes from './routes/captcha'
app.use(captchaRoutes)
感谢帮助。
解决方案
由于 getCaptcha 和 checkCaptcha 是在两个不同端点中使用的两个不同中间件,因此您的请求之间不会共享 req 对象。因此,如果您在特定请求期间在 req 中设置了一些属性,您将永远不会从另一个请求中获得这个值,因为 req 对象将是全新的。
因此,您需要有一个不同的地方来存储您的验证码信息。
例如它可能是redis。
推荐阅读
- amazon-s3 - 创建具有特定前缀的对象时触发 lambda
- amazon-web-services - 从 cloudwatch 日志组到 lambda 的 aws 传入数据已损坏
- google-apps-script - 列出谷歌驱动器中的所有文件而不超过最大执行时间?
- postman - 如何模拟以下请求:DELETE {{url}}/users/{{user_id}}
- python - Python代理字典问题
- uwp - RichTextBlock 在以编程方式更新两次时隐藏其内容
- php - 如何有条件地加载 PHP 包含?
- sql - 如何插入带有子查询的多行作为值之一?
- c++ - 指针算术和强制转换
- ruby-on-rails - 即使指定的 ruby 版本与我的匹配,也无法将应用程序推送到 heroku