Communication between client and server in Angular 2+ - node.js

I am using NodeMailer for mail service. I have to get an email address from a field in client side and send that value to app.js where my nodemailer code resides.
client side
ngOnInit() {
this.forgotForm = this.formBuilder.group({
email: this.email,
});
}
sendmail() {
}
app.js, Nodemailer code (I have to get email id for to address here)
let mailOptions = {
from: 'xyz#gmail.com',
to: '',
subject: 'Test Mailer',
text: 'I am testing Nodemailer to send email.',
};

You Should Consider Looking/ Learning Angular and then going into forms . and then into http modules which will help you post data to services
This is a gist not the actual answer
There are a lots of ways to get this done , using normal inputs and getting data from that input using button control or using Forms[the best approach] as you might have other details to send as well.
There are two kind of froms in Angular Template Driven or Reactive Forms.
After getting the details in your form you will need to post it to a Rest service i am guessing. For that you will need to look at Angular Http Client Module
Please look at those links for more detailed Info on them.

You need to use services in angular in order to do this. in terminal set the path to a folder where you want create service, and then use the command ng generate service <service_name> . This will create a file service_name.service.ts. You can refer https://codecraft.tv/courses/angular/http/overview/ or https://angular.io/tutorial/toh-pt4 for more details.
You can use APIs along with http methods get, post, put, delete etc. to complete your task.
In respective component.ts file create a variable email like:
email =string;
In the html file bind the input field with ngModel as:
[(ngModel)]="email"
Then make a function in service.ts that accepts email as arguments
endMail(email) {
//make api call using http method(say post)
// supply email
let url = <APIURL>
return http.post(url, {email: email});
}
Again in component.ts import this service and instantiate in constructor and use a method to call service

Related

Accessing Proxy Server address from my nodejs?

i'm using nodemailer to send a confirmation email on my project,
like so:
var mailOptions = {
from: "alex#account",
to: req.body.email,
subject: "Account Verification Token",
html: `<p>Hello,<br/> Please verify your account by clicking the link <br/> <a href=http://${req.headers.host}/confirmation/${token}>Click here to verify</a></p>\n`
};
Im sending an href link which contains req.headers.host which is my node adress localhost:6000, but I wish it to be my react adress localhost:4000, since its going to change later, I wish to have a variable jst like req.headers.host which will contain my react client's adress, is it possible? or I need to set it manually?
If the app is not server-side rendered, you can pass the React client's address from the frontend and include it to your request object which you can then retrieve after it gets to the server.
I found the answer I can use the variable :
const addr = `req.headers.referer`

Stripe Elements not talking to stripe server - No such token: tok_xxxx

So I'm migrating from the stripe checkout to elements so that I can register and charge a customer in a single form.
I'm following their documentation:
https://stripe.com/docs/stripe-js/elements/quickstart
Specifically in Step 3 where the token is created with the following code:
// Create a token or display an error when the form is submitted.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the customer that there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
stripeTokenHandler(result.token);
}
});
});
The documentation states:
The handler sends the fields to Stripe for tokenization...
However, it seems nothing is being sent to Stripe at all!
The bottom two requests show the two api calls made using the old checkout: First the card info is sent to /tokens and then my server handles this and makes the /customers request fine.
But when using the elements code nothing seems to be sent to stripe, even though a token is generated and sent to my server. So then I get the 'No such token' error!?
I can't for the life of me workout why stripe.createToken(card) isn't sending the details to their server and yet generates a token?? I've triple checked api keys and everything I can think of. Please help!!
What the actual heck... I got it to work but I don't know why this fixed it.
I'm using stripe elements on a .net mvc website and i'm initializing the Stripe class in a view so I can easily pass the key from my viewmodel like so:
var stripe = Stripe('#Model.StripePublicKey');
Which should work fine, right? No JS errors or anything and it was creating the token, just not posting to stripe's servers....
Anyway, I moved that line into the JS file so it's directly above the other stripe related JS and now it works!?

jQuery-File-Upload(Blueimp) with custom ajax under October CMS

Trying to create a component under October CMS which should allow frontend multiple fileuploads. I try to integrate in already exiting form the Blueimp jQuery-File-Upload Plugin and because October CMS uses an integrated ajax Framework which allows data Submission to Component method I would use this ajax method instead what from default by Blueimp
so a normal fileupload looks like
$('#gallery').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: 'path/to/controller'
});
but instead I would like to use something like
$('#gallery').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
add: function (e, data) {
data.submit();
$.request('onUploads', {
success: function(data){
console.log(data);
}
})
}
});
You need to use the Request class from Laravel which OctoberCMS sits on top of. Basically you go to the code section of your layout file and add
function onUploads()
{
// Get the file
$file = Request::file('somefile');
// Code to do something with it
// enter code here
}
Based on what you are trying to achieve you can write appropriate code to upload it. For example, in my Social Login plugin i use methods of this class to fetch photos from the chosen Social network and create a relation between the plugin's Social model and the uploaded file so that a frontend user may output the photo as a display photo in their web app.
Another good way to do it would be to directly upload it into the themes directory by doing something like Request::file('somefile')->move(app_path() . '/themes/yourtheme/assets/uploads/'); but then you will need to add code to limit the upload size and also to fix the file names. Feel free to make a comment if you need help on achieving something particularly. gl hf

What are some best practices for translating internal server error messages to client readable messages in Node.js?

Lets say I have couple of modules that handle authentication, One for each authentication provider (Google, Facebook, Email etc).
I also have a router that uses these modules to authenticate users request.
Lets say now that one of the users tries to authenticate and one of the auth module sees that the token is expired. I create an error inside that module with an internal message "token expired" or something like that, then pass it back to the calling router module. The router wants to send back a client readable message like "Your session has expired, please try to log out and in again".
So the problem is where to translate the error messages from their internal representation to their client readable versions.
There are two options the way I see it:
Do it inside each of the auth modules since they know best what was the problem. Downside - breaks the module abstraction, the module now has to deal with clients messages.
Do it in the router. Downside - need to create error codes / names and use an error handler with long list of case arguments to map each internal error to the client error. Might need to handle specific auth module errors as well, for example in email authentication the activation link in the email can be expired and the action needed is different then Facebook expired token.
What are some best practices to solve this problem, are there any Node / Express modules that help in some way ?
Many thanks
I think a good solution would be to use Express middleware for error handling.
function (err, req, res, next) {
// error translation and response sending
}
use a lang folder where the index file exposes specific language message files.
Suppose for English eng.js should be like:
module.exports = {
VALIDATION_ERROR_IN: 'Validation error in',
NOTHING_UPDATED: 'Nothing Updated',
UPDATE_NON_EXISTING_DOCUMENT_FAILED: 'can\'t update a non-existing document',
ID_REQUIRED: '\'_id\'is required',
USERID_REQUIRED: '\'userId\'is required'
}
and index.js should be like:
module.exports = require('./eng');
if you need any other language you can create new files like eng.js where the object keys remain the same but the values are language specific.
Catch the server errors and use this as follows:
var message=require('message') // suppose the folder name is 'message'
//....
res.send(message.FIELD_REQUIRED);

How to send data from node.js to angular.js controller

I'm using node.js and passport for authentication, and I need to send 'login failed' message to the client if a user failed to authenticate. My application uses also express middleware.
I'm using angular.js in the client.
Currently I'm using that command to show a static html:
var loginStatus = 'Failed';
res.sendfile('views/login.html'); // What should I add/change here in order to send the loginStatus variable ?
And this is my angular.js controller:
function MainController($scope) {
$scope.loginStatus = // What should I write here in order to get 'Failed' ?
}
I've posted my questions on the remarks above.

Resources