Home > front end >  matching req.body number without quotes
matching req.body number without quotes

Time:11-25

I have the following line of code which run when I send {"key":"1234"} to the server.

if (
        (req.path === '/start' || req.path === '/start/') &&
        (req.method === 'PUT') && (req.body.key === '1234')
    ) 

However the app I am using sends this content as {"key": 1234} to the server without the quotes around the number and therefore the if statement is getting ignored.

How would I write the if statement above so that req.body.key matches 1234 without the need of the quotes.

Thanks for the help

CodePudding user response:

Use two equals signs rather than three in

req.body.key == '1234'

That will let Javascript convert strings to numbers as it does the comparisons.

Your IDE may whine that you should use three equals signs. Ignore it. You're using two equals signs as intended by the language.

CodePudding user response:

I am not sure if the issue is with how the server accepts the request. However, if it's just a matter of if statements, then you either:

  • Just leave the single quotes out in the condition req.body.key === 1234
  • Use == instead of ===, which does not strictly verify the value (including the type) req.body.key == '1234'. Though I wouldn't recommend this, as it this leaves room for errors.
  • Related