用角fullstack从约曼发送电子邮件与节点梅勒和Sendgrid在角MEAN堆栈堆栈、节点、发送电子邮件、fullstack

2023-09-13 03:22:45 作者:像一阕遗世

我想知道在哪里可以找到逻辑通过我的角应用联系表格发送电子邮件(使用角fullstack是指从约曼堆栈)。

我可以添加逻辑使用nodemailer和sendgrid在服务器端的文件app.js发送电子邮件,一切工作和发送电子邮件我每次刷新服务器时间,但是我在哪里有点模糊放置逻辑,这样一旦在提交表单只被发送和它击中服务器端。

这是什么创造动作看起来像防爆preSS JS侧...

\r\r

exports.create =功能(REQ,RES){\r  Contact.create(req.body,功能(ERR,触点){\r    如果(ERR){返回的HandleError(RES,ERR); }\r    返回res.json(201触点);\r\r  });\r};

\r\r\r

从 FullStack 到 ZenStack

下面是该工作app.js的code,但显然不是在正确的地方...

\r\r

VAR nodemailer =要求('nodemailer');\rVAR sgTransport =要求('nodemailer-sendgrid运输');\r\rVAR的选择= {\rAUTH:{\rapi_user:用户名,//'SENDGRID_USERNAME' - 推荐保存为EVN变量\rAPI_KEY:'密码',//'SENDGRID_PASSWORD\r}\r};\r\rVAR邮件= nodemailer.createTransport(sgTransport(选项));\r\rVAR电子邮件= {\r到:sendto@email.com',\r来自:'sendfrom@email.com',\r主题:测试电子邮件,\r文字:真棒电子邮件,\rHTML:'< B>大胆真棒电子邮件和LT; / B>'\r};\r\rmailer.sendMail(电子邮件,功能(呃,RES){\r如果(ERR){\r的console.log(ERR)\r}\r的console.log(RES);\r});

\r\r\r

从铁轨背景的我最初的想法是要坚持的逻辑,在创建操作,这样,如果该对象已成功创建的电子邮件被发送。这是在这种情况下考虑这个问题的正确方法。我是新来的平均堆栈。

感谢您的帮助...

解决方案

您需要创建一个可以从角使用$ http.post发布表单数据到服务器上的路由。下面让您在角形式输入详细信息。然后形式发布到节点,在被提取出来并添加电子邮件对象req.body值。电子邮件然后由SendGrid发送。

的 SERVER.JS 的

  VAR前preSS =要求('前preSS');VAR HTTP =要求('HTTP');VAR bodyParser =要求('身体分析器');VAR dotenv =要求('dotenv');dotenv.load(); //从.ENV负载环境变量分为ENV(process.env)。VAR sendgrid_username = process.env.SENDGRID_USERNAME;VAR sendgrid_password = process.env.SENDGRID_PASSWORD;VAR sendgrid =要求('sendgrid')(sendgrid_username,sendgrid_password);VAR电子邮件=新sendgrid.Email();VAR应用=前preSS();app.use(bodyParser.json()); //需要req.bodyapp.set('口',process.env.PORT || 3000);app.use(如press.static(__目录名称+'/公'));app.post('/电子邮件,功能(REQ,RES){    email.addTo(req.body.to);    email.setFrom(req.body.from);    email.setSubject(req.body.subject);    email.setText(req.body.text);    email.addHeader(X-已发送使用','SendGrid-API');    email.addHeader(X-运输','网络');    sendgrid.send(电子邮件,功能(呃,JSON){    如果(ERR){        返回res.send(问题发送电子邮件!!!!);    }        的console.log(JSON);        res.send(邮件发送OK !!!!);    });});VAR服务器= http.createServer(应用程序);server.listen(app.get('端口'),功能(){  的console.log('前preSS服务器侦听端口+ app.get('端口'));}); 

的 INDEX.HTML 的

 <!DOCTYPE HTML>< HTML LANG =ENNG-应用=对myApp>< HEAD>    <间的charset =UTF-8>    <标题>< /标题>    <! -  CSS  - >< /头><机身NG控制器=MainCtrl>    <表格名称=emailForm>        < D​​IV CLASS =组>          <输入类型=电子邮件NAME =不行模型=email.toNG-所需=真>          <标签>到< /标签>        < / DIV>        < D​​IV>          <输入类型=电子邮件NAME =从NG模型=email.fromNG-所需=真>          <标签>来自以下; /标签>        < / DIV>        < D​​IV>          <输入类型=文本名称=主题NG-模式=email.subjectNG-所需=真>          <标签>受试对象; /标签>        < / DIV>        < D​​IV>            < textarea的NG-模式=email.textNAME =文本占位符=输入文字在这里。>< / textarea的>        < / DIV>        <按钮ID =emailSubmitBn类型=提交NG点击=submitEmail()>            提交        < /按钮>    < /表及GT;    <! -  JS  - >    &所述; SCRIPT SRC =htt​​ps://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js>&下; /脚本>    <脚本类型=文/ JavaScript的SRC =JS / app.js>< / SCRIPT>< /身体GT;< / HTML> 

的客户端APP.JS 的

  angular.module('对myApp',[]).controller('MainCtrl',函数($范围,$ HTTP){        $ scope.submitEmail =功能(){            的console.log(TEST);        //请求        $ http.post('/电子邮件',$ scope.email)        .success(功能(数据,状态){            的console.log(已发送OK);        })        .error(功能(数据,状态){            的console.log(错误);        })    };}); 

I am trying to understand where to locate the logic to send an email via a contact form in my Angular App (using angular-fullstack MEAN stack from Yeoman).

I can add the logic to send an email in the app.js file on the server side using nodemailer and sendgrid and everything works and an email is sent every time I refresh the server, however I am a little fuzzy on where to place the logic so that it only gets sent once the form is submitted and it hits the server side.

This is what the create action looks like on the Express JS side...

exports.create = function(req, res) {
  Contact.create(req.body, function(err, contact) {
    if(err) { return handleError(res, err); }
    return res.json(201, contact);

  });
};

Here is the code in app.js that is working, but obviously not in the right place...

var nodemailer = require('nodemailer');
var sgTransport = require('nodemailer-sendgrid-transport');

var options = {
	auth: {
		api_user: 'username', // 'SENDGRID_USERNAME' - Recommended to store as evn variables
		api_key: 'password', // 'SENDGRID_PASSWORD'
	}
};

var mailer = nodemailer.createTransport(sgTransport(options));

var email = {
	to: 'sendto@email.com',
	from: 'sendfrom@email.com',
	subject: 'Test Email',
	text: 'Awesome Email',
	html: '<b>Bold and Awesome Email</b>'
};

mailer.sendMail(email, function(err, res) {
	if (err) {
		console.log(err)
	}
	console.log(res);
});

Coming from a rails background my initial thought is to stick the logic in the create action so that if the object is created successfully the email gets sent. Is this a correct way of thinking about it in this scenario...I am new to the MEAN stack.

Thanks for any help...

解决方案

You need to create a route on the server that you can post form values to from Angular using $http.post. The following lets you enter details in an Angular form. The form is then posted to Node where the req.body values are extracted and added email object. The email is then send by SendGrid.

SERVER.JS

var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');
var dotenv = require('dotenv'); 

dotenv.load(); //load environment variables from .env into ENV (process.env).

var sendgrid_username   = process.env.SENDGRID_USERNAME;
var sendgrid_password   = process.env.SENDGRID_PASSWORD;

var sendgrid   = require('sendgrid')(sendgrid_username, sendgrid_password);
var email      = new sendgrid.Email();

var app = express();
app.use(bodyParser.json()); //needed for req.body
app.set('port', process.env.PORT || 3000);
app.use(express.static(__dirname + '/public')); 

app.post('/email', function(req, res) {
    email.addTo(req.body.to);
    email.setFrom(req.body.from);
    email.setSubject(req.body.subject);
    email.setText(req.body.text);
    email.addHeader('X-Sent-Using', 'SendGrid-API');
    email.addHeader('X-Transport', 'web');

    sendgrid.send(email, function(err, json) {
    if (err) { 
        return res.send("Problem Sending Email!!!!");
    }
        console.log(json);
        res.send("Email Sent OK!!!!");
    });
});
var server = http.createServer(app);
server.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port')  ) ;
});

INDEX.HTML

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="utf-8">
    <title></title>
    <!-- CSS -->
</head>
<body ng-controller="MainCtrl">
    <form name="emailForm">    
        <div class="group">      
          <input type="email" name="to" ng-model="email.to" ng-required="true">
          <label>To</label>
        </div>
        <div>      
          <input type="email" name="from" ng-model="email.from" ng-required="true">
          <label>From</label>
        </div>
        <div>      
          <input type="text" name="subject" ng-model="email.subject" ng-required="true">
          <label>Subject</label>
        </div>
        <div>      
            <textarea ng-model="email.text" name="text" placeholder="Enter Text Here.."></textarea>
        </div>

        <button id="emailSubmitBn" type="submit" ng-click="submitEmail()">
            Submit
        </button>
    </form>
    <!-- JS -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>   
    <script type="text/javascript" src="js/app.js"></script>
</body>
</html>

CLIENT SIDE APP.JS

angular.module('myApp', [])

.controller('MainCtrl', function($scope, $http) {

        $scope.submitEmail = function() {

            console.log("TEST");
        //Request
        $http.post('/email', $scope.email) 
        .success(function(data, status) {
            console.log("Sent ok");
        })
        .error(function(data, status) {
            console.log("Error");
        })
    };
});