【问题标题】:Node js use variable outside main function and set order of functionsNode js在主函数外使用变量并设置函数顺序
【发布时间】:2017-11-13 19:22:44
【问题描述】:

简介

我有三个函数,每个函数都会将数据输入下一个。目标是首先检索数据,然后验证 API 密钥,最后使用生成的 API 密钥和数据从第一个函数中检索到第三个函数中的 API。

订购

  1. 第一个从帖子中检索数据的函数函数。

  2. 第二个函数获取从 API 请求的 API 密钥。

  3. 第三个函数将数据发布到 API。

需要的功能

我需要在第一个函数中重试的变量和在第二个函数中生成的 API 密钥才能在第三个函数中使用。

问题和疑问

  • emailUser 未发现在第三个函数中使用
  • 在第三个函数中找不到api_key
  • 功能也需要先运行,后运行,后运行。

如果我要插入数据手册,这一切都有效,但是当输入变量时它不起作用,我知道这是因为变量在函数内,但我该如何解决这个问题,以及如何设置顺序的功能?

完整代码

// Grab the packages needs and sets server
//---------------------------------- 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 app = express();
var port = process.env.PORT || 8080;

// Varibles to use in second and third function
var password = 'password';
var userkey = '6767712';
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('Server started! At http://localhost:' + port);

// First Retrieve posted data from Front-End
//---------------------------------- Retrieve posted data from Front-End -----------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------
// POST http://localhost:8080/api/index
app.post('/api/data', function (req, res) {
    console.log(req.body);
    var Fname = req.body.fname;
    var Lname = req.body.lname;
    var emailUser = req.body.email;
    res.send(Fname + ' ' + Lname + ' ' + emailUser);
});

app.get('/', function (req, res) {
    res.send('hello world, Nothing to see here...');
});

// Second Get Posted variables
//---------------------------------- Now authenticate the api and get api_key -----------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------
nodePardot.PardotAPI({
    userKey: userkey,
    email: emailAdmin,
    password: password,
    // turn off when live
    DEBUG: true
}, function (err, client) {
    if (err) {
        // Authentication failed
        // handle error
        console.error("Authentication Failed", err)
    } else {
        // Authentication successful
        // gets api key
        var api_key = client.apiKey;
        console.log("Authentication successful !", api_key);
    }
});

// Third Retrieve posted data from Front-End
//---------------------------------- Send all data to API -----------------------------------------------------
// ------------------------------------------------------------------------------------------------------------
// Set the headers
var headers = {
    'User-Agent':       'Super Agent/0.0.1',
    'Content-Type':     'application/x-www-form-urlencoded'
};

// Configure the request
var options = {
    url: 'https://pi.pardot.com/api/prospect/version/4/do/create/email',
    method: 'POST',
    headers: headers,
    form: {
        'email': emailUser,
        'user_key': userkey,
        'api_key': api_key
    }
};

// Start the request
request(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        // Print out the response body
        console.log("error",body)
    }
    else {
        console.log("Sent Data",body);
    }
});

【问题讨论】:

    标签: javascript node.js api request pardot


    【解决方案1】:

    解决此问题的另一种方法是允许express middleware flow 在单独的Router 上为您执行这些操作。

    我已经设置了一个sample Glitch 供您参考,使用stand in 函数来模拟网络调用HERE

    在您的情况下,您必须执行以下操作:

    //API route
    var express = require('express');
    var router = express.Router();
    
    router.post('/data', function (req, res, next) {
        console.log(req.body);
        req.bundledData = {};
        req.bundledData.fname = req.body.fname;
        req.bundledData.lname = req.body.lname;
        req.bundledData.emailUser = req.body.email;
        next();
    });
    router.use(function(req, res, next){
        nodePardot.PardotAPI({
            userKey: userkey,
            email: emailAdmin,
            password: password,
            // turn off when live
            DEBUG: true
        }, function (err, client) {
             if (err) {
                 // Authentication failed
                 // handle error
                 console.error("Authentication Failed", err)
             } else {
                 // Authentication successful
                 // gets api key
                 req.bundledData.api_key = client.apiKey;
                 console.log("Authentication successful !", api_key);
                 next();
             }
       });
    });
    
    router.use(function(req, res, next){
        // Set the headers
        var headers = {
            'User-Agent':       'Super Agent/0.0.1',
            'Content-Type':     'application/x-www-form-urlencoded'
        };
    
        // Configure the request
        var options = {
             url: 'https://pi.pardot.com/api/prospect/version/4/do/create/email',
             method: 'POST',
             headers: headers,
             form: {
                'email': emailUser,
                'user_key': userkey,
                'api_key': api_key
             }
        };
    
        // Start the request
        request(options, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                // Print out the response body
                console.log("error",body)
            }
            else {
                console.log("Sent Data",body);
                //Processing is complete
                res.json({
                    success:true,
                    body:body
                });
            }
        });
    });
    

    【讨论】:

    • 嗯,看起来很整洁。现在去吃午饭,但在探索了这两种选择之后,谢谢。
    【解决方案2】:

    最好的方法是使用async 包(使用npm install async 安装),它是npm 中非常著名和有用的包,您的功能将是这样的:

    var async=require('async');
    
    var handler = function (req,res) {
    async.auto
    (
     {
      getBody: function (cb, results) {
        var body=req.body;
        //prepare body here then send it to next function  
        cb(null, body)
      },
      getApi: ['getBody', function (results, cb) {
        var preparedBody=results.getBody;
        // get the api here and send it to next function
        var apiKey=getApi()  
        cb(null, {apiKey:apiKey,preparedBody:preparedBody})
    
      }],
      third: ['getApi', function (results, cb) {
        var preparedBody=results.getApi.preparedBody;
        var apiKey=results.getApi.apiKey;
          // now data are here
          cb(null,true)
      }]
    },
    function (err, allResult) {
      // the result of executing all functions goes here
    }
    )
    }
    

    【讨论】:

    • 谢谢,Node 还是新手,所以正在学习。我会实施这个并测试然后让你知道。
    • 谢谢,这是一个很好的答案,我只是想在 atm 实现它
    • 如果您得到答案,请标记它,谢谢! ;) @哔声
    猜你喜欢
    • 2013-08-09
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    相关资源
    最近更新 更多