Parse numbers from query strings with bodyParser.urlencoded() in express.js

走远了吗. 提交于 2020-02-25 09:39:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!