HTTP Post data object not complete when received by backend - angularjs

I am trying to send an email using a contact form in AngularJS, the server side is programmed in NodeJS, to send the email by smtp I am using the nodemailer library, the AngularJS side the form is sending the data, but the server side not received this data, only show me an object named IncomingMessage with many items, but I don't see my email data.
Angular side
angular.module('contactApp', [])
.factory('postEmailForm',['$http',function($http){
return {
postEmail: function(emailData,callback){
console.log(emailData);
$http.post("/contact-form", emailData).success(callback);
}
}
}])
.controller('ContactController', function ($scope,postEmailForm) {
$scope.sendMail = function () {
console.log("Entro!");
var req = {
headers: {
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content- Type, Accept'
},
data:
{
contactName : this.contactName,
contactEmail : this.contactEmail,
contactMsg : this.contactMsg
}
}
postEmailForm.postEmail(req, function (res) {
console.log(req);
if (res.type == false) {
//do something
}else{
console.log("OK");
}
})
};
});
Server side
var express=require('express');
var nodemailer = require("nodemailer");
var app = express();
var serveStatic = require('serve-static');
var http = require('http');
app.use(serveStatic("."));
app.get('/',function(req,res){
res.sendfile('index.html');
});
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "sending email",
pass: "sending pass"
}
});
app.post('/contact-form',function(req,res){
//Your NodeMailer logic comes here
console.log(req.data);
var mailOptions={
from : req.data.contactEmail,
to: recipient email
subject : "Contact",
text : req.data.contactMsg
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log('Server error ' + error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});

I forgot add body-parser on the server side, to parse the data
var bodyParser = require('body-parser');
app.use(bodyParser.json());

Related

how to use nodemailer in nodejs for bulk data sending?

i have nodemailer code below, its fine and working.My problem is to send individual data to individual email. id_array have two emails and no_array have two individual data, How do i send "1" to prayag#cybrosys.in and "2" to blockchain#cybrosys.net?
var id_array = ["prayag#cybrosys.in","blockchain#cybrosys.net"];
var no_array = ["1","2"];
var mailer = require("nodemailer");
// Use Smtp Protocol to send Email
var smtpTransport = mailer.createTransport({
service: "Gmail",
auth: {
user: "mymail#gmail.com",
pass: "mypassword"
}
});
var mail = {
from: "Sachin Murali <blockchain#cybrosys.net>",
to: [id_array],
subject: "Sachin's Test on new Node.js project",
text: [no_array]
// html: "<b>"\"[no_array]\""</b>"
}
smtpTransport.sendMail(mail, function(error, response){
if(error){
console.log(error);
}else{
console.log("Message sent: " + JSON.stringify(response));
}
smtpTransport.close();
});
Prepare the parameters for each receiver in a loop and use a promise to run all emails in parallel
var id_array = ["prayag#cybrosys.in","blockchain#cybrosys.net"];
var no_array = ["1","2"];
var mailer = require("nodemailer");
// Use Smtp Protocol to send Email
var smtpTransport = mailer.createTransport({
service: "Gmail",
auth: {
user: "mymail#gmail.com",
pass: "mypassword"
}
});
let emailPromiseArray = [];
//prepare the email for each receiver
for(let i=0;i<id_array.length;i++){
emailPromiseArray.push(
sendMail({
from: "Sachin Murali <blockchain#cybrosys.net>",
to: id_array[i],
subject: "Sachin's Test on new Node.js project",
text:no_array[i]
})
)
}
//run the promise
Promise.all(emailPromiseArray).then((result)=>{
console.log('all mail completed');
}).catch((error)=>{
console.log(error);
})
function sendMail(mail){
return new Promise((resolve,reject)=>{
smtpTransport.sendMail(mail, function(error, response){
if(error){
console.log(error);
reject(error);
}else{
console.log("Message sent: " + JSON.stringify(response));
resolve(response);
}
smtpTransport.close();
});
})
}

Nodejs callback response not working as expected

I'm trying to authenticate a user based on values entered in a given form. However, after using res.send(), the function at AngularJS controller is not able to correctly redirect user even if the password and username are correct. Am I handling the callbacks correctly?
Controller
<script>
var app = angular.module('myApp', []);
app.controller("loginController", function($scope,$http) {
$scope.sub = function() {
var config = {
headers : {
'Content-Type': 'application/x-www-form-
urlencoded;charset=utf-8;'
}
}
$http.post('/login', { data:{ username: $scope.username,
password: $scope.password} })
.then(function(response){
if(response.state==0){
console.log('Error!');
} else if(response.state==1){
console.log('action on success');
window.location.href = '/views/success.html';}
}).catch(function(error){
console.log('action on error');
});
Authentication
var db = require('../../config');
exports.login = function(req,res){
var username = req.body.data.username;
var password = req.body.data.password;
db.query('SELECT * FROM users WHERE username = ?',[username], function
(error, results, fields){
var result = "0";
if(error) {
console.log('Code 400, Error ocurred');
}
else{
if(results.length>0){
if(results[0].password == password){
console.log('Code 200, login sucessful');
res.json({ state : 1});
}
}
else{
console.log('Code 400, Password or username invalid');
res.json({ state: 0})
}
}
});
}
server.js
var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var db = require('./config');
var app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(express.static(__dirname + '/app'));
require('./app/routes')(app);
app.listen(3000,function(err){
if(err){
console.log(err);
}
else{
console.log("Listening on port 3000");
}
});
Route.js
var auth = require('../app/middleware/authenticateUser');
module.exports = function (app) {
app.get('/',function(req,res){
res.sendFile(__dirname + '/views/index.html');
});
app.post('/login', function(req, res){
auth.login(req,res);
});
}
Thanks in advance!
You need to inject $window in your controller and then in your successful response
$window.location.href = '/views/success.html';
Although using the $window service is considered AngularJS best practice, I don't think this is where the problem is.
Have you tried console.log() the response object of the $http call?
Maybe the problem is because you put if(response.state) instead of if(response.data.state).

PUT/ update operation fails in $resource AngularJS client in rest based app (mongoose insert / update issue).

I am new to MEAN applications.Here I have a REST based sample application using node-restful library in which I can perform operations(get,save,delete) except 'put'. However 'put' operation works well on rest clients (advanced REST, postman) but not on angular client.
mongoose Model
var restful = require('node-restful');
var mongoose = restful.mongoose;
// Schema
var productSchema = new mongoose.Schema({
name: String,
college: String,
age: Number
});
// Return model
module.exports = restful.model('Products', productSchema);
Node-express code
var express = require('express');
var methodOverride = require('method-override');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors =require('cors');
// MongoDB
mongoose.connect('mongodb://localhost/rest_test');
var autoIncrement = require('mongoose-auto-increment');
// Express
var app = express();
app.use(methodOverride('_method'));
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Routes
app.use('/api', require('./routes/api'));
// Start server
app.listen(4000);
console.log('API is running on port 4000');
angular function to update the data
$scope.updateData = function (userID) {
$scope.actionData = {
"name": $scope.name,
"college": $scope.college,
"age": $scope.age
}
RoleEditF.updateUserData({
userId: userID
}, $scope.actionData).then(function (response) {
$scope.userData = response;
console.log($scope.userData)
$scope.getData();
}).catch(function (response) {
$scope.error = "Unable to get Files (code: " + response.status + "). Please try later.";
});
}
angular.module('myapp')
.factory('RoleEditF', function (updateS) {
return {
updateUserData: function (parm, data, callback) {
var cb = callback || angular.noop;
return updateS.save(parm, data,
function (res) {
return cb(res);
},
function (err) {
return cb(err);
}.bind(this)).$promise;
}
}
})
Factory to call API
angular.module('myapp')
.factory('updateS',function($resource) {
return $resource('http://localhost:4000/api/products/:userId', { userId: '#userId' }, {
update: {
method: 'PUT'
}
}, {
stripTrailingSlashes: false
});
});
I'm getting following error on browser
"NetworkError: 404 Not Found - http://localhost:4000/api/products/57161e0fe4fbae354407baa3"
it has to be 'update' in
'update': {
method: 'PUT'
}
inside your $resource() factory
documentation here
https://docs.angularjs.org/api/ngResource/service/$resource
under Creating a custom 'PUT' request

How to change my angular controller and node server code to post data into my database

How to change my angular controller and node server code to post data into my database
Controller
var app= angular.module('App',[]);
var PD;
var address=null;
var pid=1;
app.controller("Ctrl",function($scope,$http) {
$http.get('/load').success(function(data) {
$scope.persons= data;
});
$scope.submit=function(){
PD=prompt("Enter person details");
if(PD.localeCompare("")!=0)
{
var data=JSON.stringify({pid:pid,
persondescription:PD,
url:$scope.url,
address:address,
submittedtime:new Date().toLocaleString().replace("/.*(\d{2}:\d{2}:\d{2}).*/", "$1"),
status:'Submitted'
});
console.log(data);
$http.post('/send',data).success(function(data,status) {
console.log(data);
console.log('Data posted successfully');
});
});
Node server code
Server
var express = require('express');
var http=require('http');
var bodyParser= require('body-parser');
var mysql = require('mysql');
var app = express();
app.set('port', 3000);
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));
enter code herevar connection = mysql.createConnection({
host : '-',
user : '-',
password : '-',
database : '-'
});
connection.connect(function(error){
if(error)
{
console.log("Problem with MySQL"+error);
}
else
{
console.log("Connected with Database");
}
});
app.get('/',function(req,res){
res.sendfile('managementt.html');
});
/*
* Here we will call Database.
* Fetch news from table.
* Return it in JSON.
*/
app.get('/load',function(req,res){
connection.query("SELECT * from personactivity",function(err,rows){
if(err)
{
console.log("Problem with MySQL"+err);
}
else
{
res.end(JSON.stringify(rows));
}
});
});
app.post('/send', function(req,res){
console.log(req.body);
var query = connection.query('insert into personactivity set ?',req.body, function(err, res) {
if (err) {
console.error(err);
return res.send(err);
} else {
return res.send('Ok');
}
});
app.listen(3000,function(){
console.log("It's Started on PORT 3000");
});
How to change my angular controller and node server code to post data into my database

success function is not working angular

I am sending http request and when that request is finished I am trying to go to another state but the problem is it does not goes in the success callback I thought my be I'm getting an error so I wrote the error callback it does not goes in that to. Can anybody tell me what am I doing wrong
$scope.submitUpdatedData= function(user){
debugger;
// $http.post('/url',{params: value}).sucess(function(){
API.updateRecord(user).success(function(res){
$state.go('app' ,{} , {reload: true });
console.log("Hello");
});
}
The API code is given below. Here I invoke the http call
.factory('API', function($http) {
var api = {};
var baseURL = 'http://localhost:3000';
api.addRecord = function(record) {
console.log(record);
// $http.post(baseURL + '/addData', {name: record.name}.);
return $http.post(baseURL + '/addData', {rec:record});
};
api.deleteRecord = function(id){
return $http.get(baseURL +'/delete/' + id );
};
api.updateRecord = function(user){
return $http.post(baseURL + "/update/" ,{rec:user});
};
api.getAllRecord = function(){
return $http.get(baseURL+'/getAll');
};
api.getOneRecord = function(id){
return $http.get(baseURL + '/getOne/' + id)
};
return api;
})
UPDATE
I have replaced the .success part with then but it still not works
Second Update
This is my server side code
var express = require('express');
var mongoose = require('mongoose');
var util = require('util');
var bodyParser = require('body-parser')
var app = express();
var Schema = mongoose.Schema;
require('node-monkey').start({host: "127.0.0.1", port:"50500"});
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
};
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
// app.use(express.json()); // to support JSON-encoded bodies
// app.use(express.urlencoded()); // to support URL-encoded bodies
app.use(allowCrossDomain);
// app.use('/' , require('./index'))
mongoose.connect('mongodb://localhost:27017/myappdatabase');
var userSchema = new Schema({
name: String,
password: String
});
var Todo = mongoose.model('Todo', userSchema);
app.get('/getAll' , function(req, res){
Todo.find({} , function(err , todos){
if (err){
res.send(err);
}
console.log(todos);
res.send(todos);
});
});
app.get('/delete/:name' , function(req , res){
console.log(req.params);
console.log(req.params.name);
Todo.remove({
name : req.params.name
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
});
app.get('/getOne/:id' , function(req , res){
Todo.find({name : req.params.id}, function(err, todo) {
if (err)
res.send(err);
res.send (todo[0]);
// get and return all the todos after you create another
});
});
app.post('/update', function(req , res){
console.log(req.param('rec').name);
Todo.update({_id:req.param('rec').id} , {$set : {name:req.param('rec').name , password:req.param('rec').password}} , function(err){
if(err)
res.send("Error occured");
res.send("true");
});
});
app.post('/addData' , function(req , res){
console.log( req.param('rec').name);
var p = new Todo({name: req.param('rec').name , password: req.param('rec').password});
p.save(function(err){
if(err){
res.send(err);
console.log(error);
}
res.json(p);
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
// module.exports = app;
Seems like success and error are deprecated, you should use then instead:
API.updateRecord(user).then(function(res){
$state.go('app' ,{} , {reload: true });
console.log("Hello");
});
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
Source here
Seems like your request is never answered by the API Server. Maybe you can set a timeout for your request. Here it says you can do:
$http.post(url, data, {timeout: 100});
That should timeout your request after 100ms.

Resources