node.js - bodyParser解析得到的参数类型不统一
PHPz
PHPz 2017-04-17 15:15:53
0
1
627

请问express中如何使用bodyParser得到统一的数据类型?

const bodyParser = require('body-parser');

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({
    extended: false
}));

移动设备发出的json请求 在req.body得到的参数类型会是对应的boolean、number、string

而网页中发出的form请求 在req.body得到的参数类型只会有string

PHPz
PHPz

学习是最好的投资!

reply all(1)
巴扎黑

The headers of the requests sent are different and the parsing methods are different

  1. For json requests sent by mobile devices, the Content-Type in the header is application/json, and the server will know that you are sending json data, such as { name : 'taozhi', age: 18, cool: true}

  2. The request issued by the form of the web page is that the Content-Type in the header is application/x-www-form-urlencoded. After the server knows the encoding of the transmitted data, such as name=taozhi&age=18&cool=true, Then it is parsed into json, so it becomes a string type. For detailed analysis, if your extended is false, see querystring

  3. Now that you know what the problem is, it depends on what kind of structure you need. When requesting, just declare Content-Type proactively. At the same time,

app.use(bodyParser.urlencoded({
    extended: true
}));

It is best to use the qs library to parse

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template