When I pass data to my node application, req.body gets garbled. My client call:
$.post('/posts/#{post._id}/post', {seen_posts: seen_posts}, function(data, status) {
}
My controller function:
exports.item_posts_get = function(req, res, next) {
console.log("SEEN POSTS");
console.log(req.body);
console.log(req.body.seen_posts);
}
Console:
SEEN POSTS
[Object: null prototype] {
'seen_posts[]': [ '5f6ac9fdae396910b32011c4', '5f6ac9fdae396910b32011c4' ]
}
undefined
In your jQuery code try JSON.stringify({seen_posts: seen_posts})
in place of {seen_posts: seen_posts}
.
In your nodejs express code put these lines shortly after where you say 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() )
This arranges to pass your data from $.post()
to your server in JSON format, and parse it into req.body
. You can troubleshoot it with the Network tab of your browser devtools.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.