客户:
$.ajax({
url: some_url,
type: 'post',
dataType: 'json',
data: JSON.stringify({myArray: []})
...
}
$.ajax({
url: some_url,
type: 'post',
data: {myArray: []}
...
}
服务器:
var app = express();
app.use(bodyParser()); // body-parser module
app.use(function(req, res, next){
console.log(req.body);
// When stringified, prints: { '{"myArray":': { ']': '' } }
// When not stringified, prints: {}
});
我知道因为我的数组是空的,所以它没有被发布,但我完全困惑为什么字符串化时输出如此困惑。是body解析器引起的吗?
我想做的就是检索我的数组并在其上循环。如果它是空的,那就这样吧。
谢谢!
最佳答案
bodyParser()
中间件根据请求的 Content-Type
header 进行解码,可以使用 contentType
option 设置该 header 。 :
data: JSON.stringify({ myArray: [] }),
contentType: 'application/json',
如果不指定 contentType
为 JSON,解析器将尝试根据默认的 URL 编码进行解码,从而生成您看到的 body
结构。
关于jquery - Node.js - 使用 json.stringify 时主体困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24148859/