当我将数据传递给节点应用程序时,req.body变得乱码。我的客户呼叫:
$.post('/posts/#{post._id}/post', {seen_posts: seen_posts}, function(data, status) {
}我的控制器函数:
exports.item_posts_get = function(req, res, next) {
console.log("SEEN POSTS");
console.log(req.body);
console.log(req.body.seen_posts);
}控制台:
SEEN POSTS
[Object: null prototype] {
'seen_posts[]': [ '5f6ac9fdae396910b32011c4', '5f6ac9fdae396910b32011c4' ]
}
undefined发布于 2020-09-24 09:05:58
在您的jQuery代码中,尝试用JSON.stringify({seen_posts: seen_posts})代替{seen_posts: seen_posts}。
在您的nodejs express代码中,将这些行放在您说const app = express()的地方之后不久
/* allow handling json and URL-encoded POST document bodies */
const bodyParser = require( 'body-parser' )
app.use( bodyParser.json() )
app.use( bodyParser.urlencoded( { extended: true } ) )
/* allow handling cookies */
const cookieParser = require( 'cookie-parser' )
app.use( cookieParser() )这将以JSON格式将数据从$.post()传递到服务器,并将其解析为req.body。您可以使用浏览器devtools的Network选项卡对其进行故障排除。
https://stackoverflow.com/questions/64037108
复制相似问题