JavaScript & TypeScript

[node.js] express-validator param error

반응형

 

 

express-validator로 유효성 검사를 할 수 있는데

param의 경우, 경로가 어떻게 되어 있느냐에 따라 검사를 하는 경우가 있고 그렇지 않은 경우가 있습니다.

 

아래의 코드를 예시로 들면

/route/:id 의 경로를 사용할 경우 string으로 타입이 결정되고

/:id 의 경우 number로 타입이 결정됩니다.

 

그러므로 전자 경우에서는 유효성검사가 제대로 되지 않고, 후자는 유효성 검사가 제대로 동작이 됩니다.

const express = require('express')
const { param } = require('express-validator')
const app = express()

// Not sanitizing correctly
app.use('/route/:id', [
  param('id').isInt()
  // handle validation errors
], (req, res, next) => {
  console.log(typeof req.params.id) // string
  return res.sendStatus(200)
})

// Sanitizing correctly (tested also with .get and .all)
app.post('/:id', [
  param('id').isInt()
  // handle validation errors
], (req, res, next) => {
  console.log(typeof req.params.id) // number
  return res.sendStatus(200)
})

app.listen(3000)

 

 

전자의 경우에서의 경로를 그대로 유지하고 유효성검사가 제대로 동작하기 위해서는 .toInt()를 추가적으로 사용해 주면 됩니다.

app.use('/route/:id', [
  param('id').isInt().toInt()
  // handle validation errors
], (req, res, next) => {
  console.log(typeof req.params.id) // string
  return res.sendStatus(200)
})

어느경우에 쓰고 안쓰고 햇갈린다면 .toInt()를 붙어 사용하는 것으로 통일하는것이 좋다고 생각합니다.

반응형

'JavaScript & TypeScript' 카테고리의 다른 글

[TS] Decorators  (0) 2022.03.23
[TS] Compile (option)  (0) 2022.03.22
[TS] utility type  (0) 2022.03.21
[TS] type alias, interface 차이  (0) 2022.03.20
[JS] ProtoType  (0) 2022.03.15