-1

//Server side code of node js

//Dependencies
var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var multer = require('multer');
var mongo = require('mongoose');
var schema =require('./schema.js');
var done = false;
var cors = require('cors');
var mandrill = require('mandrill-api/mandrill');
//END OF EXTERNAL DEPENDENCIES`
var mandrill_client = new mandrill.Mandrill('Some_Mandrill_API_Tocken');
//Environment Settings For Express Js Server
var app = express();
// all environments
app.set('port', process.env.PORT || 8080);
app.set('views', path.join(__dirname, 'inner_html'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
app.use(bodyParser.json());       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({// to support URL-encoded bodies
    extended: true
}));

app.post( '/sendemail', function(req, res){
console.log(req.body);
var _name = 'Anonymous User';
var _email = req.email;
var _subject = 'Query';
var _messsage = req.message;
//implement your spam protection or checks.
var message = {
"text": _messsage,
"subject": "Website Query",
"from_email": _email,
"from_name": _name,
"to": [{
"email": "agniruddra.r@gmail.com",
"name": "Admin"
}],
"important": false,
"track_opens": true,
"track_clicks": true,
"auto_text": true
};


mandrill_client.messages.send({"message": message}, function(result) {
console.log(message);
console.log(result);
res.json({'msg' : 'Your Mail sent to Faculty Successfully'});
}, function(e) {
// Mandrill returns the error as an object with name and message keys
console.log('A mandrill error occurred: ' + e.name + ' - ' + e.message);
// A mandrill error occurred: Unknown_Subaccount - No subaccount exists with the id 'customer-123'
});
});

And here it is my html form body below.....

<div id="myModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title">Email Faculty</h4>
            </div>
            <form class="rqust_mail" method="POST" action="/sendemail">
            <div class="modal-body">
                    <div class="form-group">
                        <label for="recipient-name" class="control-label">Email:</label>
                        <input type="text" class="form-control" id="email" name="email">
                    </div>
                    <div class="form-group">
                        <label for="message-text" class="control-label">Message:</label>
                        <textarea class="form-control" id="message" name="message"></textarea>
                    </div>                    
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <input type="submit" class="btn btn-primary send_mail" name="Send" value="Send"/>
            </div>
            </form>

            <script type="text/javascript">
                /*$('.send_mail').click(function(){                        
                    $.ajax({
                    type: "POST",
                    data: data,
                    contentType: "application/json",
                    dataType:"json",
                    url: "https://mywebsite.com/sendemail",                 
                    success:function(data){
                            console.log(JSON.stringify(data));
                            //$('.rqust_mail input').reset();
                            }
                    });
                });*/
            </script>
        </div>
    </div>
</div>

I tried with both ajax and normal html http post request. Both of these (HTML and AJAX POST) request bodies contains an empty json.

Please suggest me what is wrong with my code.

Thanks in advance.

Agniruddra
  • 56
  • 7

3 Answers3

0

I don't see anywhere in that browser script where it actually collects the form data into data.

Anyway, try using multer https://www.npmjs.com/package/multer with just the regular POST (not AJAX).

var express = require('express')
var multer  = require('multer')

var app = express()
app.use(multer({ dest: './uploads/'}))

You can then look at req.body in your post handler.

Jason Livesay
  • 6,317
  • 3
  • 25
  • 31
  • Thanks for your response.... I have already configured multer for file upload purpose. I have posted only a part of my node.js server code here. The same error consists even after using multer as a middleware. However the Ajax part may be faulty. I am a newbie to Ajax. But the normal HTTP POST request should work I think and that is not happening in my case. Can you highlight the reason??? – Agniruddra Apr 04 '15 at 10:11
  • Hard to guess without the actual code. Maybe some app.use before the body parser interferes. I would take out any app.use you don't need and start trimming your code down until it works. Process of elimination. Or, start with an example, get that working, then gradually add in your real code. Post a minimal example with the real code you tried demonstrating the problem. – Jason Livesay Apr 04 '15 at 20:41
  • Also I notice in your `post` handler you write`req.email` did you mean `req.body.email`? – Jason Livesay Apr 04 '15 at 20:46
0

Use req.body.email instead of req.email. And use app.use(express.bodyParser())

Abhishek Dey
  • 1,601
  • 1
  • 15
  • 38
0

I think there was some encoding exception with the parser.... I just removed thecontentType: "application/json", and the code is working fine..... still dont know the reason why it is not working with normal HTTP POST....it may be the same encoding exception.....

Agniruddra
  • 56
  • 7