无法在请求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
App.js
import captchaRoutes from './routes/captcha'
app.use(captchaRoutes)
感谢帮助。
回答如下:由于getCaptcha和checkCaptcha是两个不同端点中使用的两个不同的中间件,因此请求之间不共享req对象。因此,如果您在特定请求期间在req中设置了某个属性,那么您将永远不会从另一个请求中获取此值,因为req对象将是全新的。
因此,您需要的是存储验证码信息的不同位置。
例如,它可能是redis。