使用express.js中的bodyParser.urlencoded()从查询字符串中解析数字

时间:2018-03-28 04:50:53

标签: express body-parser

在前端,我使用jQuery发送这样的GET请求:

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

根据jQuery doc,第二个参数是一个普通的对象,它将被转换为GET请求的查询字符串。

在我的节点表达后端,我使用这样的body-parser:

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
});

然而,req.query变为{foo:'123', bar: '123'},其中所有数字都转换为字符串。如何恢复到从前端发送的完全相同的对象? 谢谢!

2 个答案:

答案 0 :(得分:1)

HTTP了解所有内容都是查询字符串参数相同的字符串。简而言之,这是不可能的。只需使用parseInt()

将数据转换为整数

例如

app.get('/api', (req, res) => {
  console.log(parseInt(req.query.bar)) // req.query should be the {foo:123, bar:'123'} I sent
});

答案 1 :(得分:0)

我写了一段分析可转换内容的代码段:

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