首页 > 解决方案 > 无法在请求 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)

感谢帮助。

标签: javascriptnode.jsexpress

解决方案


由于 getCaptcha 和 checkCaptcha 是在两个不同端点中使用的两个不同中间件,因此您的请求之间不会共享 req 对象。因此,如果您在特定请求期间在 req 中设置了一些属性,您将永远不会从另一个请求中获得这个值,因为 req 对象将是全新的。

因此,您需要有一个不同的地方来存储您的验证码信息。

例如它可能是redis。


推荐阅读