0
I was doing some tests and I realized that when sending a parameter with single and double quotes, an internal error occurs.
Ex:
password: teste'"
Error:
SyntaxError: Unexpected token i in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (C:\Users\iarlo\Desktop\teste\node_modules\body-parser\lib\types\json.js:158:10)
at parse (C:\Users\iarlo\Desktop\teste\node_modules\body-parser\lib\types\json.js:83:15)
at C:\Users\iarlo\Desktop\teste\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\Users\iarlo\Desktop\teste\node_modules\raw-body\index.js:224:16)
at done (C:\Users\iarlo\Desktop\teste\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\Users\iarlo\Desktop\teste\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1327:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
expose: true,
statusCode: 400,
status: 400,
body: 'invalid',
type: 'entity.parse.failed'
}
Code:
import { body } from 'express-validator'
import express from 'express'
import bodyParser from 'body-parser'
const app = express()
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get("/enviar", [
body("password")
.not()
.isEmpty()
.withMessage("Value cannot be empty")
.isLength({ min: 6, max: 60 })
.withMessage("Value must be between 6 and 60 characters long")
.matches(
new RegExp(
"^(?=.*\\d)(?=.*[a-z])[\\w\\s!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\^_`{|}~]{6,}$",
"i"
)
)
.withMessage("Value is not a valid password"),
], (req, res, next) => {
console.log(req.body)
});
Requisition: Content type: application/json
How can I prevent this error from occurring if a user uses both quotes in the same string? Ps. the error occurs before I can give escape()
What is the code? Your question has little information.
– Luiz Felipe
Is the code necessary? I mean, my question is about how to prevent the user from "importing" something through this error. Anyway, as you can see in the stack, the error has no root in the code, only in "node_modules/body-parser". It occurs when sending a request, even before I can validate the body.
– Bruno Sá
You need to create a [mcve]. Without it, we are not able to reproduce your problem...
– Luiz Felipe
You can check now?
– Bruno Sá
Ok, I changed the content type to application/x-www-form-urlencoded and the error is gone
– Bruno Sá