我有一个简单的代码,它使用express:
向服务器发送POST请求$http.post('/blah', {
boolean: true,
stringBoolean: 'true',
number: 213,
stringNubmer: '44444444',
string: 'adssd',
arrayNumber: [1, 2, 3, 4],
arrayBoolean: [true, false, "true", "false"],
});
和服务器端的这一行:
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.post('/blah', (req, res)=>{
console.log(req.body)
})
客户端发送请求后在控制台中的输出(在chrome和firefox上测试)将所有值都作为字符串:
{ boolean: 'true',
stringBoolean: 'true',
number: '213',
stringNubmer: '44444444',
string: 'adssd',
arrayNumber: [ '1', '2', '3', '4' ],
arrayBoolean: [ 'true', 'false', 'true', 'false' ] }
然后我使用Postman将相同的数据结构发送到服务器:
{ “boolean”:是的, “stringBoolean”:“true”, “号码”:213, “stringNubmer”:“44444444”, “string”:“adssd”, “arrayNumber”:[1,2,3,4], “arrayBoolean”:[true,false,“true”,“false”] }
但是这次我在控制台中有数字和布尔值:
{boolean:true, stringBoolean:'true', 数量:213, stringNubmer:'44444444', string:'adssd', arrayNumber:[1,2,3,4], arrayBoolean:[true,false,'true','false']}
看起来像是在窗帘后面做一些约定。如何避免这种情况并将正确的值类型发送到服务器?
更新: 在chome控制台中,我可以看到原始格式的请求体,如下所示:
boolean=true&stringBoolean=true&number=213&stringNubmer=44444444&string=adssd&arrayNumber%5B0%5D=1&arrayNumber%5B1%5D=2&arrayNumber%5B2%5D=3&arrayNumber%5B3%5D=4&arrayBoolean%5B0%5D=true&arrayBoolean%5B1%5D=false&arrayBoolean%5B2%5D=true&arrayBoolean%5B3%5D=false
这意味着每个值将始终为字符串,我必须在服务器端手动将其转换为适当的类型。这个任务是对的吗?这里有什么好的做法?
答案 0 :(得分:1)
它在内部使用JSON.stringify()
。使用JSON.parse()