javascript - Sending json with $.post in express/node -


this app.js file:

var express = require('express'); var app = express(); var path = require('path'); var $ = require('jquery'); var nodemailer = require('nodemailer');   app.use('/static', express.static(path.join(__dirname, 'static')));   app.get('/', function(req, res) {     res.sendfile('./views/index.html', {"root": __dirname}); });   app.post('/contact/', function(req, res){     console.log(req.body);  }); 

and post request file, called when form submitted:

$('form').submit(function(e){     e.preventdefault();     var content = $('#message').val();     var email = $('#emailinput').val();     var reason = $('#reason').val();      $.post('/contact', { 'content': content, 'email': email, 'reason': reason }, function(data){         console.log(data);     }); }) 

however, whenever form submitted, post request successful, it's no data has been passed.

req , req.body both return undefined. can't figure out why.

you need body parser populate body property of request object

npm install body-parser 

then include

var bodyparser = require('body-parser'); app.use(bodyparser.json()); app.use(bodyparser.urlencoded({extended: true})); 

documentation particular use case , tweaking may found here

edit: sure include before route handlers declared


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -