node express 获取jsonArray取不到值
Node获取ajax post上来的json数据,其数据格式如下:
var dataJSON = {
"test": "sssssssssssssssss",
"action": [{
"action": "hotV1.action",
"data": "111"
},
{
"action": "hotV2.action",
"data": "222"
},
{
"action": "hotV3.action",
"data": "333"
}
]
}
Node中,使用require('body-parser')后,
app.post('/test', function(req, res) {
console.log(req.body.test);
console.log(req.body);
});
输出见下图
直接req.body.test取出没问题,但是要取出action就取不到值,求各位大解惑。。。。
app.js
var express = require('express');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
/**
* 引入模块
*/
var requestFun = require('./requestFun');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
//设置跨域访问
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
app.post('/test', function(req, res) {
console.log(req.body.test);
console.log(req.body);
//requestFun.setJson(req.body);
});
app.get('/',function(req,res){
res.render('index')
});
app.listen(process.env.PORT || 3000);
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
</body>
<script>
$(function(){
var dataJSON = {
"test": "sssssssssssssssss",
"action": [{
"action": "hotV1.action",
"data": "111"
},
{
"action": "hotV2.action",
"data": "222"
},
{
"action": "hotV3.action",
"data": "333"
}
]
}
// var dataJSON = {
// "test":"ssssssssssssssssss",
// "hotV1":{
// "action": "hotV1.action",
// "data": "111"
// },"hotV2":{
// "action": "hotV2.action",
// "data": "222"
// },"hotV3":{
// "action": "hotV3.action",
// "data": "333"
// }
// }
$.ajax({
type:'post',
url:'http://localhost:3000/test',
data:dataJSON,
dataType: "json",
success:function(data){
console.log(data);
},
error:function(){
console.log('error');
}
})
});
</script>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
console
出来的object
明显key不对,key为action[0][action]
而不是action
,看起来像你post的content-type
是application/x-www-form-urlencoded
而不是application/json