Doubt about the body of the requisition

Asked

Viewed 66 times

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

inserir a descrição da imagem aqui 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.

  • 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.

  • You need to create a [mcve]. Without it, we are not able to reproduce your problem...

  • You can check now?

  • Ok, I changed the content type to application/x-www-form-urlencoded and the error is gone

1 answer

0


the body of the request is normally used for a list of variables encoded in URI or JSON

URI: var1=valor&var2=valor2
lembrando os nomes e valores de variaveis devem ser passados por encodeURIComponent antes de serem concatenados, para que os espaços, aspas e caracteres especiais sejam corretamente codificados
JSON: {"var1":"var2"}

in your case, body-parser ran JSON.parse on body, which generated an error, because this body is not a valid JSON, to avoid this error I recommend that a JSON.stringify on the frontend side to convert a valid JSON object...

if you want to validate your JSON in an external tool, I indicate:

https://jsonformatter.curiousconcept.com/

remembering that JSON.parse also does not accept comments, or simple quotes, so I always recommend using JSON.stringify.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.