1

In the front end, I use jQuery to send a GET request like this:

$.get('/api', {foo:123, bar:'123'), callback);

according to jQuery doc, the 2nd parameter is a plain object that will be converted into query string of the GET request.

In my node express back end, I use body-parser like this:

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/api', (req, res) => {
  console.log(req.query) // req.query should be the {foo:123, bar:'123'} I sent
});

However, req.query turns out to become {foo:'123', bar: '123'} where all the numbers were converted to strings. How can I revert to the exact same object I sent from front end? Thanks!

1

2 Answers 2

1

HTTP understands that everything is a string same goes for query string parameters. In short, it is not possible. Just convert your data to integer using parseInt()

example

app.get('/api', (req, res) => {
  console.log(parseInt(req.query.bar)) // req.query should be the {foo:123, bar:'123'} I sent
});
Sign up to request clarification or add additional context in comments.

Comments

1

I wrote this snippet which parses the convertible ones:

query = Object.entries(req.query).reduce((acc, [key, value]) => {
  acc[key] = isNaN(+value) ? value : +value
  return acc
},{})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.