[英]Cant access custom value in request 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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.