简体   繁体   English

将功能从后端节点传递到前端角度

[英]Pass functions to front-end angular from back-end node

Introduction 介绍

I need to verify if a email address is within a API, if so allow a user to enter a section someone cant if they are not a user. 我需要验证电子邮件地址是否在API内,如果允许,则允许用户输入某人无法访问的部分(如果他们不是用户)。

I have built the back-end node code to verify this. 我已经建立了后端节点代码来验证这一点。

I have 3 functions build in my back-end (node, express) . 我在后端(node, express)构建了3个函数。

The first 首先

Gets data from a front-end form (Angular) post and then uses promise to make the value available to the third function. 从前端表单(Angular)发布中获取数据,然后使用promise将值提供给第三个函数。

The second 第二

This function authenticates and gets my API key and using promise makes this function available to the third function. 该函数进行身份验证并获取我的API密钥,并且使用promise可使该函数可用于第三个函数。

The third 第三

This function uses the data from the first (email address) and the API key from the second and post to a API endpoint, If the email is present on the API you get pass, if not fail. 此函数使用第一个(电子邮件地址)中的数据和第二个中的API密钥并将其发布到API端点。如果API上存在电子邮件,则可以通过,否则不会失败。

Process 处理

A user enters a email on the front end Angular, hits login then this email is passed to the three back-end functions, then it will pass or fail in the third function. 用户在前端Angular上输入电子邮件,单击login然后将该电子邮件传递给三个后端功能,然后它将在第三个功能中通过或失败。

If this passes I wish to pass $scope.EmailTrue= true; 如果通过了,我希望通过$scope.EmailTrue= true; to my Angular controller so that I can ng-hide or ng-show buttons on my front-end. 到我的Angular控制器,以便可以在前端进行ng-hideng-show按钮。

I was thinking of maybe a simple post to my front-end, but I am new to angular and node so I am unaware if there is a different way of doing this. 我当时想在前端发布一个简单的文章,但是我对angular和node不熟悉,因此我不知道是否有其他方法可以做到这一点。

Node back-end (3 functions) 节点后端(3个功能)

//---------------------------------- Grab the packages we need and set variables ---------------------------------------
//----------------------------------------------------------------------------------------------------------------------
var express = require('express');
var request = require('request');
var nodePardot = require('node-pardot');
var bodyParser = require('body-parser');
var rp = require('request-promise');
var app = express();
var port = process.env.PORT || 8080;

// Credential's for pardot API
var password = 'password';
var userkey = 'userkey';
var emailAdmin = 'admin@admin.com';

// Start the server
app.listen(port);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
console.log('Test server started! At http://localhost:' + port); // Confirms server start

//---------------------------------- Function to get front end form posted data LOGIN form ----------------------------------------
//----------------------------------------------------------------------------------------------------------------------
var firstFunction = function () {
    return new Promise (function (resolve) {
        setTimeout(function () {
            app.post('/back-end/test', function (req, res) {
                console.log(req.body);
                var login = req.body.LoginEmail;
                res.send(login);
                resolve({
                    data_login_email: login
                });
            });
            console.error("First done");
        }, 2000);
    });
};

//---------------------------------- Function to get API key from Pardot (AUTHENTICATION) ------------------------------
//----------------------------------------------------------------------------------------------------------------------
var secondFunction = function () {
    return new Promise (function (resolve) {
        setTimeout(function () {
            nodePardot.PardotAPI({
                userKey: userkey,
                email: emailAdmin,
                password: password,
                DEBUG: false
            }, function (err, client) {
                if (err) {
                    // Authentication failed
                    console.error("Authentication Failed", err);
                } else {
                    // Authentication successful
                    var api_key = client.apiKey;
                    console.log("Authentication successful !", api_key);
                    resolve({data_api: api_key});
                }
            });
            console.error("Second done");
        }, 2000);
    });
};

//---------------------------------- Function to post data to Pardot ---------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------

function thirdFunction(result) {
    return new Promise (function () {
        setTimeout(function () {
            var headers = {
                'User-Agent': 'Super Agent/0.0.1',
                'Content-Type': 'application/x-www-form-urlencoded'
            };
// Configure the request
            var api = result[1].data_api;
            var login_email = result[0].data_login_email;
            var options = {
                url: 'https://pi.pardot.com/api/prospect/version/4/do/read',
                method: 'POST',
                headers: headers,
                form: {
                    'email': login_email,
                    'user_key': userkey,
                    'api_key': api
                },
                json: true // Automatically stringifies the body to JSON
            };

// Start the request
            rp(options)
                .then(function (parsedBody) {
                    console.error("pass");
                    // $scope.FormLogin = true;
                })
                .catch(function (err) {
                    console.error("fail");
                });
            console.error("Third done");
        }, 3000);
    }
    );
}

// sequence of functions
Promise.all([firstFunction(), secondFunction()])
    .then(thirdFunction);

Angular controller 角度控制器

FirstModule.controller('LoginController', function TestController($scope, $http) {
    $scope.LoginForm = function () {
        var data = {
            LoginEmail: $scope.formData.LoginEmail
        };

    $http({
        url: 'http://localhost:8080/back-end/test',
        method: "POST",
        data: data,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function (data) {
        $scope.formData = data; // assign  $scope.persons here as promise is resolved here
    }).error(function (data, status) {
        $scope.formData = status;
    });

}
});

Angular view 角度图

<form class="col-sm-8 col-sm-offset-2">
    <div>
        <div class="form-group">
            <label>Email*</label>
            <input type="email" class="form-control col-sm-12" name="LoginEmail" placeholder="Enter valid E-mail">
        </div>

        <button class=""
                ng-submit="LoginForm()">
            Login<span class=""></span>
        </button>
    </div>
</form>

In Angular you can user the $http service to make an http request and then handle the response. 在Angular中,您可以使用$http服务来发出http请求,然后处理响应。

You can do: 你可以做:

$http.post('/login', {
    email: 'user@email.com',
    password: 'pwd'
}).then(response => {
    // use http status code
    if (response.status === 403) {
        alert('forbidden')'
    } else {
        // do something
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM