使用express.js中的bodyParser.urlencoded()解析查询字符串中的数字
在前端,我使用jQuery发送GET请求,如下所示:使用express.js中的bodyParser.urlencoded()解析查询字符串中的数字,express,body-parser,Express,Body Parser,在前端,我使用jQuery发送GET请求,如下所示: $.get('/api', {foo:123, bar:'123'), callback); 根据jquerydoc,第二个参数是一个普通对象,它将被转换为GET请求的查询字符串 在我的node express后端中,我使用的主体解析器如下: const bodyParser = require("body-parser"); app.use(bodyParser.urlencoded({ extended: true })); app.g
$.get('/api', {foo:123, bar:'123'), callback);
根据jquerydoc,第二个参数是一个普通对象,它将被转换为GET请求的查询字符串
在我的node express后端中,我使用的主体解析器如下:
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'}
,所有的数字都被转换成字符串。如何恢复到从前端发送的完全相同的对象?
谢谢 HTTP理解一切都是字符串,查询字符串参数也是如此。简言之,这是不可能的。只需使用parseInt()将数据转换为整数 范例
app.get('/api', (req, res) => {
console.log(parseInt(req.query.bar)) // req.query should be the {foo:123, bar:'123'} I sent
});
我写了这个片段来解析可转换的:
query = Object.entries(req.query).reduce((acc, [key, value]) => {
acc[key] = isNaN(+value) ? value : +value
return acc
},{})
可能重复的