Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

320
Visualizações
Server crashes when testing app expecting a number. Express, NodeJS

Prevent server from crashing.

I am testing an API with Postman where I am expecting a number with or without decimal places.

But it happens that at the time of testing if I enter a sign like this in Postman: " ) " the server crashes automatically and it seems that it does not reach my validator.

Postman:

{
        "concept": "Text",
        "incomeAmount": 1)0000,
        "expenseAmount": 89,
        "description":"Text"
}

Failed response:

SyntaxError: Unexpected token ) in JSON at position 73 at JSON.parse () at parse (C:\project\node_modules\body-parser\lib\types\json.js:89:19) at C:\project\node_modules\body-parser\lib\read.js:121:18 at invokeCallback (C:\project\node_modules\raw-body\index.js:224:16) at done (C:\project\node_modules\raw-body\index.js:213:7) at IncomingMessage.onEnd (C:\project\node_modules\raw-body\index.js:273:7) at IncomingMessage.emit (node:events:402:35) at IncomingMessage.emit (node:domain:475:12) at endReadableNT (node:internal/streams/readable:1343:12) at processTicksAndRejections (node:internal/process/task_queues:83:21)

I am using express validator like this:

router.post('/new-income',
    [
        check('incomeAmount', 'El Monto del Ingreso debe ser Númerico').isNumeric().not().isEmpty(),
        check('expenseAmount', 'El Monto del Egreso debe ser Númerico').isNumeric().optional({ checkFalsy: true }),

    ],
    validation,
    newItem
);

And in the controller, I use Regex to verify that it is a positive number without symbols, but apparently neither the request nor the route arrives.

const regAmount = new RegExp('^[+]?([1-9][0-9]*(?:[\.][0-9]*)?|0*\.0*[1-9][0-9]*)(?:[eE][+-][0-9]+)?$');


        if (!regAmount.test(incomeAmount)) {
            return res.json ( {
                'msg': 'Only positive numbers without signs are allowed'
            } ); 
        }

Thanks for your help!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This is expected. You're sending illegal JSON so your JSON parsing middleware gets an exception. To catch/handle this error, you need to either install custom middleware that catches the error in the middleware or catch the error from the existing JSON parser in the Express error handler by installing your own Express error handler.

Also, if you're using the express.json() middleware, it has a verify callback option that you can pre-check the JSON if you want, but frankly, it's probably easier to just have an Express error handler and get the error there.

about 4 years ago · Juan Pablo Isaza Relatório

0

With this much information I can only assume that you are using some kind of json middleware that parse the incoming data.

Unfortunately, the data you sent via postman is not in a valid json format. Ironically enough, only valid number are accepted as value without the need of quotation mark (excluding array and object).

A solution maybe to send the data as pure text to your api and then run in through your validation before converting it into a number.

You can verify the json format yourself here: https://jsonformatter.curiousconcept.com/

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda