2017-06-12 53 views
2

介紹節點JS主要功能外使用變量和函數設定順序

我有三個功能,每一個將數據饋送到下一個接着。目標首先是檢索數據,然後驗證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 = '[email protected]'; 
// 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); 
    } 
}); 

回答

1
使用 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 
} 
) 
} 
+0

謝謝你,依然有新的節點,以便在學習。我實施這個測試然後讓你知道。 – Beep

+0

ok @Beep;但你問一個很好的問題;) – farhadamjady

+0

謝謝,這是一個很好的答案我只是想實現它atm – Beep

0

解決此問題的另一種方法是允許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 
      }); 
     } 
    }); 
}); 
+0

嗯,看起來整潔。現在去吃午飯,但是在不幸地探索了兩種選擇之後,謝謝。 – Beep