问题
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:
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
});
来源:https://stackoverflow.com/questions/49526332/parse-numbers-from-query-strings-with-bodyparser-urlencoded-in-express-js