请问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
The headers of the requests sent are different and the parsing methods are different
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}
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 asname=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 querystringNow 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,It is best to use the qs library to parse