首页 > express bodyParser 解析问题?

express bodyParser 解析问题?

前端测试代码

$('#test').click(function(){
        var data = {
            flag:false
        }
        $.ajax({
            url: "/test",
            method: "POST",
            data: data,
            dataType: "json",
            success:function(result){

            },
            error:function(xhr,error){
                console.log(error);
            }
        });
    })

node代码

app.post('/test', function(req, res) {
    console.log(typeof req.body.flag);
});

我加了app.use(express.bodyParser());
结果是string,为什么不会解析成Boolean类型呢?


因为对于 urlencoded 来说所有内容都是 string.
所以如果你想要 json 类型的数据,那么你在提交的时候就应该告诉服务器你提交的数据类型是 json 格式的.

测试代码如下:

app.js

var express = require('express');
var app = express();

var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());

app.post('/test', function(req, res){
    console.log(req.body);
    console.log(typeof req.body.flag);
    res.send(JSON.stringify(req.body, null, 2));
});


app.listen(8080);
var data = {
    flag:false
};

$.ajax({
    url: "http://127.0.0.1:8080/test",
    method: "POST",
    contentType:'application/json; charset=utf-8',//指定POST提交的数据类型
    data: JSON.stringify(data),//将 object 转换为 json格式的字符串
    dataType: "json",
    success:function(result){
        console.log(result);
    },
    error:function(xhr,error){
        console.log(error);
    }
});

【热门文章】
【热门文章】