MEAN.JS Contact Form - angularjs

Trying to create a contact form and feedback form for my website. Here is my route and controller I'm using however I need to understand what's going on with my routes and how to capture the input fields from the form implement this inside MEAN.JS:
route.js:
app.route('/mail').get(mail.createmail);
app/controller.js:
exports.createmail = function(req, res) {
var mailOpts, smtpTrans;
// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'administrator#radleaf.com',
pass: '34Girls34*goo'
}
});
// NB! No need to recreate the transporter object. You can use
// the same transporter object for all e-mails
// setup e-mail data with unicode symbols
var mailOptions = {
from: 'Fred Foo ✔ <foo#blurdybloop.com>', // sender address
to: 'ty#radleaf.com', // list of receivers
subject: 'Hello ✔', // Subject line
text: 'Hello world ✔', // plaintext body
html: '<b>Hello world ✔</b>' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Message sent: ' + info.response);
}
});
};
Not sure how this work with the HTML with the view:
<form action="mail">...</form>

If I understand the question correctly, you're asking how you can gather data which is input into a form, send that data to expressJS, and then use that data to send an outbound email.
If so, then here is your flow:
Step 1: Create a form in a view and map it to an AngularJS controller
<form name="contactForm" data-ng-submit="sendMail()">
Name: <input type="text" data-ng-model="contact_name">
Message: <input type="text" data-ng-model="contact_msg">
<button type="submit">
</form>
Step 2: In your AngularJS controller, use a $http request to send your data to your Express Route
$scope.sendMail = function() {
// Simple POST request example (passing data) :
$http.post('/mail', {name: contact_name, msg: contact_msg}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
Step 3: Use your ExpressJS Route as an API to call your ExpressJS Controller.
(It looks like you've got this bit covered)
app.route('/mail').get(mail.createmail);
Step 4: Receive and do something with the data passed through the $http POST
exports.createmail = function(req, res) {
var data = req.body;
Now you can use the data, like this
var mailOptions = {
from: data.name, // sender name
text: data.msg, // plaintext body
};
MeanJS 0.4.0 also has a working example of NodeMailer which might help: https://github.com/meanjs/mean/tree/0.4.0

With angularJS, you can remove the action attribute, and just use angularJS ngSubmit directive, and call a function in your controller which would now visit the endpoint with $http.get.

Related

Handling file submit API response in angular

I have a form where a user uploads a file to my node server, does some stuff, and sends a JSON response.
I do not make the POST through the control, its via submitting a form. After my node code does some stuff, it sends this response succesfully.
res.json({
results: "TRUE",
file: rows,
column: pIndex,
rowCount: rows.length
})
Problem, i need to access this json response in my angular app. After a user submits form, they see raw json of this response and the app redirects to my endpoint: http://localhost:8000/upload-file
What do i do to access this response in my angular app without uploading file via controller($http.post)
I have no idea, im much new to javascript. Thanks!
Upload File with AngularJS
The template
<input type=file files-input ng-model="files" /><br>
<button ng-disabled="!files[0]" ng-click="upload()">Upload</button><br>
The Upload button becomes active after the file is selected.
The files-input Directive
app.directive("filesInput", function() {
return {
require: "ngModel",
link: function linkFn (scope, elem, attrs, ngModel) {
elem.on("change", function (e) {
ngModel.$setViewValue(elem[0].files);
});
}
};
});
The directive uses the ngModelController API to bind the selected files to a scope variable.
The upload() function
var vm = $scope;
var url = "API URL";
var config = { headers: {"Content-Type": undefined} };
vm.upload = function() {
//USE formData for Content-Type multipart/formdata
//var formData = new $window.FormData();
//formData.append("file-0", vm.files[0]);
//USE files[0] for binary upload
$http.post(url, vm.files[0], config)
.then(function(response) {
vm.result = "SUCCESS";
vm.data = response.data.data;
}).catch(function(response) {
vm.result = "ERROR "+response.status;
});
};
It is important to set Content-Type: undefined so that the AngularJS framework doesn't set the content type to application/json. The XHR send method will then set the content type according the type of the given object.
It is more efficient to send the file directly, but if content type multipart/formdata with base64 encoding is desired, use the formData API to create a formData object for the XHR API to send.
The DEMO on PLNKR.
This is because you aren't using the Angular controller. A regular HTML form, by default will attempt to make a URL params encoded POST request to the URL defined in the action="" attribute, or, if not defined, it will POST to the current URL. The result of the post is then simply spit out into the browser window.
Angular has a directive ngSubmit that is for intercepting this default behavior so that you can handle it in a controller:
<form ng-submit="mySubmitHandler()">
...
<input type="text" ng-model="formData.myField"/>
</form>
In your Angular controller you can now do whatever you wish. Typically you make a POST request using the $http provider:
function myController($scope) {
$scope.formData = {
myField: '',
};
$scope.mySubmitHandler = function () {
$http.post('/someUrl', formData).then(function(response) {
//handle the response from Node.js
});
};
}
The problem with this is that you are trying to upload a file. Trying to upload files with $http can be daunting. Your best bet is to use a 3rd party library to facilitate file upload in angular, such as ng-file-upload. It will come with it's own set of instructions that will allow you to handle the Node response inside of Angular.

Use data from angular to make external api call in node express

I am trying to use data that the user inputs to make an api call to an external API using node. I have successfully made calls from the server, and returned them to angular. But I need to send the server a variable from angular, have it make a call, and return the response to my view. I am new to node so I am sorry if this has already been answered somewhere. I looked around and found nothing.
My html
<md-input-container class="md-block" flex-gt-sm>
<label>Player 1</label>
<input ng-model="player1.username">
</md-input-container>
<md-button ng-click="comparePlayers(player1, player2)">COMPARE!</md-button>
My controller function
$scope.comparePlayers = function(player1) {
Nerd.getPlayer(player1)
}
My 'Nerd' Service
smiteStats.factory('Nerd', ['$http', function($http) {
return {
getPlayer: function(playerName) {
$http.post('/api/getPlayer', playerName).success(function(data) {
console.log("sent to server"); //does not run
})
}
}]);
My Express Route
app.post('/api/getPlayer', GetPlayer.apiGetPlayer);
My node module that makes the api call
module.exports = {
apiGetPlayer: function(error, res, player) {
console.log(player); //this returns "[Function: next_layer] in my cmd
}
}
To send Parameters with $http in POST:
$http({
url: host + '/api/getPlayer',
method: "POST",
data: { 'fruit1' : "Apple"}
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
});
To get POST parameters, you will need the ExpressJS body-parser package. This will allow you to grab information from the POST.
Read more

I send http post request with angular but it does not go to the asp.net mvc action and returns html layout tags

I am doing an angular application with asp.net mvc and i made a registration form with identity, I have layout and index mvc view which i just write in it ng-view tag and i inject html pages in it, I am doing a http post request from angular controller to mvc action method but the request does not go to the mvc action, whereas when i change th views to mvc views and make a templateUrl in angular map to mvc method it works well.
Can any one help me in this problem.
[HttpPost]
[AllowAnonymous]
public async Task<JsonResult> Register(RegisterViewModel model)
{
string message = "";
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
FirstName = model.FirstName,
MiddleName = model.MiddleName,
LastName = model.LastName,
UserName = model.Email,
Email = model.Email,
UserStatus = UserStatus.Waiting
};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
message = "Success";
}
else
{
AddErrors(result);
message = "InvalidEmail";
}
}
else
{
message = "Failed!";
}
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
and this is my angular controller
MyApp.controller('RegisterController', ['$scope','$http',function ($scope, $http) {
$scope.message = '';
$scope.isFormValid = false;
//Check Form Validation
$scope.$watch('f1.$valid', function (newValue) {
$scope.isFormValid = newValue;
});
//Save Data
$scope.SaveData = function (data) {
$scope.submitted = true;
$scope.message = '';
if ($scope.isFormValid) {
$http({
method: 'POST',
url: '/Account/Register',
data: data
}).then(function (response) {
// check your response (if a success status code was resolved)
console.log(response.data);
}, function (error) {
// check your error response
console.log(error);
});
} else {
$scope.message = "Please Fill the blanks";
}
}
}]);
and this is my html page:
<div ng-controller="RegisterController">
<form name="f1" ng-submit="SaveData(user)" novalidate>
controls here
</form
1) Check your browser console for any javascript errors, if you have any, resolve them and try again!
2) Check you have the correct ActionMethodSelectorAttribute attribute ([HttpPost]) over your controller method and that your method name is spelt correctly.
3) Check that you have the correct path in your request.
4) Check you are sending the correct data to the controller!!!
5) Check that the method is public.
6) Check that you are authorised to access that controller/method.
7) Check that you don't have any duplicate method names with either, a) the same parameters and name (if your not using an ActionMethodSelectorAttribute, or b) the same names and method select attributes.
8) Remove all parameters from your method, put a breakpoint at the start of the method, and try making the request and see if it hits the breakpoint. If it works without parameters and not with, then you are not passing the correct required data into the method.
9) Make your request and check the response!! (example below):
// make your request
$http({
method: 'POST',
url: '/Controller/Method',
data: {
foo: bar
}
}).then(function(response) {
// check your response (if a success status code was resolved)
console.log(response);
}, function(error) {
// check your error response
console.log(error);
});
If you have a 404 then your method was not found, if you have a 500 then something blew up in your code, if you have a 401 then you are unauthorised etc... This is really useful to actually know what is going on with your request...
10) Check your application is running!

Not able to update data in mongoDB using AngularJs

When I try to change the status of a blog , the status is not updating in database. Status is string field and is initially stored as 0 in database
api.post('/statuschange', function(req, res){
Blog.find({_id: req.query.blog_id}).update({$set:{'status': req.body.status}}, function (err, status) {
if(err){
res.send(err);
return;
}
if(req.body.status == '1') {
res.json('Blog added')
return;
}
if(req.body.status == '-1'){
res.json('Blog not added');
return;
}
});
})
api is working successfully on postman
factory file
angular.module('blogfact', ['authService'])
.factory('blogFactory', function($http, AuthToken){
var factory = {};
var token = AuthToken.getToken();
factory.changestatus = function(info, callback){
$http({
url: 'api/statuschange',
method:'POST',
headers:{'x-access-token':token},
params:{'blog_id': info},
})
.success(function(response){
callback(response)
})
}
return factory
})
the controller file
angular.module('blogCtrl', ['blogfact']);
.controller('BlogController', function(blogFactory, $routeParams){
var that=this;
blogid = $routeParams.id;
var getthatBlog = function(){
blogFactory.getthatBlog(blogid, function(data){
//console.log('[CONTROLLER] That Blog:',data);
that.blog = data;
})
}
this.changestatus = function(info){
blogFactory.changestatus(info, function(data){
getthatBlog();
})
}
})
html file
<div ng-controller="BlogController as blog">
<textarea ng-model="blog.status"></textarea>
<button class="btn btn-success" ng-click="blog.changestatus(blog._id)">Submit</button>
</div>
If your question is regarding the value in MongoDB not being updated, well it seams it is due to the status data missing in your POST request.
I recommend that in your HTML, send the whole blog object so that you have the blog's status as well:
<button class="btn btn-success" ng-click="blog.changestatus(blog)">Submit</button>
Then in your blogFactory add the data as such:
$http({
url: 'api/statuschange',
method:'POST',
headers:{'x-access-token':token},
params:{'blog_id': info._id},
data: {status: info.status} // <==
})
Now, you should be able get the blog status data in NodeJS server back-end via req.body.status.
Update
Try the following with mongoose's update method:
Blog.update({_id: req.query.blog_id}, {status: req.body.status}, function(err, numAffected){
...
});
Or, alternatively:
Blog.findOne({_id: req.query.blog_id}, function(err, blog){
blog.status = req.body.status;
blog.save();
});
Angular let's you modify collection data on the client-side, but to actually update it on your server you need to notify the server of your changes (via API).
There are a few ways to do this, but if you want seamless updating from client-side to server maybe give meteor a try.
http://www.angular-meteor.com/
https://www.meteor.com/
Your are sending the data in params and getting the data from req.body.
You should use req.query or req.param. Else, Send the data on body like below,
$http({
url: 'api/statuschange',
method: 'POST',
params: { 'blog_id': info },
data: { 'status': 1 }
})
Your are passing 1 parameter in client side and getting two parameters on server side(req.body.status, req.query.blog_id)
Where is the token value from ?
Check the simplified way to test your code
http://plnkr.co/edit/tyFDpXw2i0poICwt0ce0

How to call a function upon http get or post?

I'm sure this is a stupid question but I am very new to the backend so please forgive me.
I am building an angularjs app with express/node also and am trying to integrate PayPal (as a Node.js SDK), what I want is to call the pay method on the SDK from an angular controller and I am doing as follows:
On button click:
// controller
$scope.pay = function(amount) {
PaymentFactory.doPayment(amount);
}
Payment Factory:
// PaymentFactory
return {
doPayment: function(amount) {
$http.get("../../../server/payments/paypal.js")
.then(function(response) {
console.log( response );
})
}
}
Then the server-side file is as below:
require('paypal-adaptive');
var app = require('../../server.js');
var PayPal = require('paypal-adaptive');
var paypalSdk = new PayPal({
userId: 'userid',
password: 'password',
signature: 'signature',
sandbox: true //defaults to false
});
var payload = {
requestEnvelope: {
errorLanguage: 'en_US'
},
actionType: 'PAY_PRIMARY',
currencyCode: 'GBP',
feesPayer: 'EACHRECEIVER',
memo: 'Chained payment example',
cancelUrl: 'returnUrl,
returnUrl: 'cancelUrl',
receiverList: {
receiver: [
{
email: 'email1',
amount: '3.40',
primary:'true'
},
{
email: 'email2',
amount: '1.20',
primary:'false'
}
]
}
};
paypalSdk.pay(payload, function (err, response) {
if (err) {
console.log(err);
} else {
// Response will have the original Paypal API response
// But also a paymentApprovalUrl, so you can redirect the sender to checkout easily
console.log('Redirect to %s', response.paymentApprovalUrl);
return response;
}
});
Of course the get request just returns a string of the server-side file contents, I understand why the above doesn't work but not sure how one would make it work. My aim is to call the PayPal SDK from the angular factory and get back the response so that I can redirect a user to a URL. A direct solution would be helpful but even more so I need pointers to the principles that I am not understanding here as far as how one should call functions upon user actions to get this data from the server side. I have tried searching but I don't really the language to use in my search.
All you need to do is use curl (node-curl npm module). Using curl will help you post data to your paypal url and get back the response. Now you need to handle this response from paypal and accordingly generate your own response to be received by the angular http method.

Resources