exporting in node causes syntax errors - javascript

I have a file, controller.js in trying to import functionality into app.js.
I keep getting syntax errors:
, expected
statement expected
Simple to fix I though however when I fix one 10 more pop up, So can some one look at my code and see what doing wrong ?
app.js
Promise.all([controller.firstFunction(), controller.secondFunction()]) .then(controller.thirdFunction);
controller.js
module.exports = {
var express = require('express');
// var rp = require('request-promise');
var app = express();
// var request = require('request');
var nodePardot = require('node-pardot');
// Credential's for pardot API
var password = ';lu.88';
var userkey = 'kol;';
var emailAdmin = 'j.j#jj.co.uk';
//
// // 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
//
// app.use('/', router);
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);
});
};
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 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(login_email, "Is a user, login pass!");
})
.catch(function (err) {
console.error("fail no such user");
// res.status(400).send()
});
console.error("Third done");
}, 3000);
}
);
}
};

This is because you wrapped your code inside an object, {} tags.
You have a couple of options, my suggestion is to use Prototypes like so
var express = require('express');
// var rp = require('request-promise');
var app = express();
// var request = require('request');
var nodePardot = require('node-pardot');
// Credential's for pardot API
var password = ';lu.88';
var userkey = 'kol;';
var emailAdmin = 'j.j#jj.co.uk';
//
// // 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
//
// app.use('/', router);
function Functions(){};
Functions.prototype.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);
});
};
Functions.prototype.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);
});
};
Functions.prototype.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(login_email, "Is a user, login pass!");
})
.catch(function (err) {
console.error("fail no such user");
// res.status(400).send()
});
console.error("Third done");
}, 3000);
}
);
}
module.exports = Functions;
Then you would create a instance of the class within the file you require it (in this case app.js)
var myFunctions = new Functions();
From there you can access your methods using:
myFunctions.firstFunction();
If you however wanted to go on about the way you have done so already, you should use object structure like so
module.exports = {
firstFunction : function()
{
//Function Body
},
secondFunction : function()
{
//Function Body
}
}

Issue with you code is :
you were using var inside module.export and that means you are declaring var inside export that is not valid,
module.export should be in json format.
Try this code :
var express = require('express');
// var rp = require('request-promise');
var app = express();
// var request = require('request');
var nodePardot = require('node-pardot');
// Credential's for pardot API
var password = ';lu.88';
var userkey = 'kol;';
var emailAdmin = 'j.j#jj.co.uk';
//
// // 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
//
// app.use('/', router);
module.exports = {
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);
});
},
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);
});
},
thirdFunction : function(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(login_email, "Is a user, login pass!");
})
.catch(function (err) {
console.error("fail no such user");
// res.status(400).send()
});
console.error("Third done");
}, 3000);
}
);
}
};

You need to use object notation inside of an object ( module.exports):
var express = require('express');
// var rp = require('request-promise');
var app = express();
// var request = require('request');
var nodePardot = require('node-pardot');
// Credential's for pardot API
var password = ';lu.88';
var userkey = 'kol;';
var emailAdmin = 'j.j#jj.co.uk';
module.exports = {
firstFunction() {
return new Promise(function(){
...
});
},
secondFunction(){},
thirdFunction(){}
};
and exporting dependencies and passwords is not really useful...

Related

How can I update the frontend after waiting for the database in the backend to update in Node.js/Express?

I saw a similar question posted Here, but they are using MEAN-Stack.
I am currently just using a 'setTimeout' function to wait a few seconds before requesting new data from the server using a fetch api to give it time to update but this doesnt feel like the right way to do it. Is there a simple way for the front-end to update only after the database is updated in Express? I am new to Node please forgive me.
app.js:
const express = require('express');
const app = express();
const mysql = require('mysql');
let viewData = {
//html data
}
var pool = mysql.createPool({
connectionLimit : 10,
host: "localhost",
port: 3306,
database: 'testing',
user: "root",
password: "pass"
});
function sql(type) {
if(type == 'select') {
//Select query here
}
if(request == 'addRow') {
//Insert query here
}
}
app.get(`/`, function (req, res) {
res.sendFile('./views/index.html', {root: __dirname});
})
app.post('/api/add', function(req, res){
res.setHeader('Content-Type', 'application/json');
sql('addRow')
});
app.get('/api/viewData', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(viewData));
})
index.js:
function loadData() {
fetch('/api/viewData')
.then(z => z.json())
.then(a => {
//update html
})
}
function postData(a) {
fetch('/api/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
//data to send to app.js
})
}).then(setTimeout(function(){loadData();}, 3000))
}
You should use async and await function
Example: After async/await
async function fun1(req, res){
let response = await request.get('http://localhost:3000');
if (response.err) { console.log('error');}
else { console.log('fetched response');
}
The complete code of our example is shown below:
npm install express jsonschema body-parser promise-mysql
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
var validate = require('./validate')
var mysqlConnection = require('./connectionShare');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const addItem = function(item, connection){
console.log("Adding Item");
return new Promise(function(resolve, reject){
connection.query("INSERT INTO product SET ?", item)
.then(function(result){
resolve(item.seller);
}).catch(function(error){
reject(error);
});
})
}
const findOrCreateUser = function(user,connection){
console.log("Finding User");
return new Promise(function(resolve,reject){
connection.query("SELECT * FROM user WHERE email=" + connection.escape(user.email))
.then(function(results){
if(results.length == 1){
resolve(results[0].id)
} else {
connection.query("INSERT INTO user SET ?", user)
.then(function(results){
resolve(results.insertId);
});
}
}).catch(function(error){
reject(error);
})
})
}
const selectUserItems = function(userID,connection){
console.log("Selecting Items " + userID);
return new Promise(function(resolve,reject){
connection.query("SELECT * FROM product WHERE seller = " + connection.escape(userID))
.then(function(results){
resolve(results);
}).catch(function(error){
reject(error);return;
});
})
}
app.post('/add/product', validate.JsonValidation, mysqlConnection.getConnection, async function(req,res){
var connection = req.connection;
var item = {
name: req.body.name,
price: req.body.price,
width: req.body.width,
height: req.body.height,
added: req.body.added,
image: req.body.image
};
var user = {
username: req.body.seller.username,
email: req.body.seller.email,
votes: req.body.seller.votes
};
try {
item.seller = await findOrCreateUser(user,connection);
var user_id = await addItem(item,connection);
var items = await selectUserItems(user_id, connection);
connection.connection.release();
res.status(200).json(result);
} catch(error) {
res.status(500).end(error);
}
});
process.on('uncaughtException', error => console.error('Uncaught exception: ', error));
process.on('unhandledRejection', error => {console.error('Unhandled rejection: ', error));
app.listen(8000, function () {
console.log('App listening on port 8000')
});

How to render object from REST response

I want to render to the ui / print to console log some object value from GET response.
I'm using Node JS for my server side and HTML + JS for my client side.
Because my goal is to render data and the request type is cross domain I can't use "fetch" function.
My only alternative to execute it is to send it by "JSONP" dataType.
Actually, the request is sent and the response receives by callback as well, but my code is print "null" to the console and not the response data.
When I've tried to used JSON.parse() it received a "parseerror".
The expected result it's to get only the image tag value (2.0.90) and to print this inside the console log / render it to the UI.
async function uiChecking() {
let index;
const hostsDock = [qa + dockers];
let lengthVal = hostsDock.length;
for (let hostIndxD = 0; hostIndxD < lengthVal; hostIndxD++) {
index = hostIndxD;
let url = hostsDock[hostIndxD];
$.ajax({
url: url,
dataType: 'jsonp',
}).done( function(data) {
console.log("A " + data);
});
}
}
**Server.js **
var express = require('express');
var cors = require('cors');
var app = express();
var path = require("path");
var fetch = require('fetch-cookie')(require('node-fetch'));
var btoa = require('btoa');
var http = require('http');
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
}else{
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, data , corsOptions) // callback expects two parameters: error and options
};
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/view');
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('index');
res.render('logo');
res.writeHead(200, {'Content-Type': 'application/json'});
});
// app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) {
// res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
// });
app.get('/data/:id', function (req, res, next) {
var opts = {
host: config.alertService.host,
port: config.alertService.port,
method: 'GET',
path: '/DataService/rest/receiveData/' + req.params.id
}
var reqGet = http.request(opts, function (dataResponse) {
var responseString = '';
dataResponse.on('data', function (data) {
responseString += data;
});
var response = {x:[],y:[],z:[],t:[]};
dataResponse.on('end', function () {
var responseObject = JSON.parse(responseString);
var accs = responseObject.data.listPCS;
for(var i in accs){
response.x.push(accs[i].accX);
response.z.push(accs[i].accY);
response.y.push(accs[i].accZ);
response.t.push(accs[i].timestamp);
}
res.jsonp(response);
});
});
reqGet.end();
reqGet.on('error', function (e) {
console.error(e);
});
});
if (app.settings.env === 'production') {
app.error(function(err, req, res) {
res.render('new404.html', {
status: 500,
locals: {
error: error
}
});
});
}
app.listen(8033, function () {
console.log('CORS-enabled web server listening on port 8033')
});
You need to iterate through the response to return the result e.g..
$.each(data, function(index) {
console.log(data[index].ui);
console.log(data[index].id); console.log(data[index].Name);
});

session management for multiple concurrent users in node+express js

I am trying to login as admin using mobile device and after successful login, I am setting cookie in response header. Mean while, when I try to access routes from other device(laptop), I get all admin access from other device.
How do I maintain session for multiple users ?
Also the problem is I am trying to maintain the view state in global object(login/logout button based on if user in logged-in or not) which get lost with server-side rendering.
I mean all the JavaScript variable data(DataMixin object in my case) is lost.
How to develop isomorphic riotjs app? See similar issue fixed in reactJs: https://github.com/reactjs/react-chartjs/issues/57
State:
document.addEventListener('DOMContentLoaded', function (e) {
DataMixin = { //Global object
setAuthentication: function(){
if(arguments[0] != null){
localStorage.setItem('role', arguments[0][0]);
localStorage.setItem('loginStatus', arguments[0][1]);
}
},
getRole: function(){
return localStorage.getItem('role');
},
}
}
View:
ADMIN LOGIN
<li if="{DataMixin.getRole() == 'ROLE_ADMIN'}">
<a onclick="{logout}">LOGOUT</a>
</li>
Loading pages from server-side using node+express:
function urlDataApiResponse(url, params, req, res) {
swig = require('swig');
var header_tag = require('./public_html/tags/header_tag.tag');
var blog_post_details_tag = require('./public_html/tags/blog_post_details.tag');
var footer_tag = require('./public_html/tags/footer_tag.tag');
var blog_sidebar_tag = require('./public_html/tags/blog_sidebar.tag');
var slide_menu_tag = require('./public_html/tags/slide_menu.tag');
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views',__dirname + '/public_html/tags/');
var postDetails = {};
console.log('url inside getApiResponse ', url);
var options = {
method: 'GET',
uri: url,
qs: params,
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(function (response) {
createJWT(req,res);
var postDetails, categories, blog_sidebar_tag_rendered, slide_menu_tag_rendered,
header_tag_rendered, blog_tag_rendered, footer_tag_rendered;
postDetails = (response[0].attributes);
console.log('.............................................................');
console.log('.............SERVER-SIDE-RENDERING:START.....................');
console.log('.............................................................');
header_tag_rendered = riot.render(header_tag, {role: storage.getItemSync('role'), loginStatus: storage.getItemSync('loginStatus') });
slide_menu_tag_rendered = riot.render(slide_menu_tag, {role: storage.getItemSync('role'), loginStatus: storage.getItemSync('loginStatus') });
blog_tag_rendered = riot.render(blog_post_details_tag, {details: postDetails, role: storage.getItemSync('role')});
blog_sidebar_tag_rendered = riot.render(blog_sidebar_tag);
footer_tag_rendered = riot.render(footer_tag);
var meta_details = {
postImageUrl: postDetails.userImage,
title: postDetails.title + " - Rootscopeit.in",
description: postDetails.details.substring(0,200)+"...",
details: postDetails.details,
url: postDetails.url
};
res.render('blog_post_details', {
open_graph: meta_details,
header_details: header_tag_rendered,
slide_details: slide_menu_tag_rendered,
article_details: blog_tag_rendered,
sidebar_details: blog_sidebar_tag_rendered,
footer_details: footer_tag_rendered});
console.log('............................................................');
console.log('............SERVER-SIDE-RENDERING:END.......................');
console.log('............................................................');
})
.catch(function (err) {
console.log('=================================');
console.error('POST error ', err.stack);
console.log('=================================');
return res.status(res.statusCode).send(err);
});
}
Setting cookie in passport js:
//==============
//TOKEN CREATION
//==============
function createJWT(req, res){
var claims = {
sub: 'Social Authentication',
iss: 'https://rootscopeit.in',
};
var jwt = nJwt.create(claims, secretKey);
jwt.setExpiration(new Date().getTime() + (60 * 60 * 1000 * 1)); // One hour from now
var token = jwt.compact();
var cookies = new Cookies(req, res).set('access_token', token, {
//httpOnly: true,
//secure: true // for your production environment
});
}
//=======================================
//===Google Authentication
//=======================================
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth20').Strategy;
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
var user = USERS[id];
done(null, user);
});
app.get('/auth/google', passport.authenticate('google',
{scope: ['profile', 'https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/plus.profile.emails.read',
'https://www.googleapis.com/auth/blogger']}));
app.get('/auth/google/callback', passport.authenticate('google', {failureRedirect: '/', failureFlash: true}),
function (req, res) {
console.log('success authentication');
createJWT(req,res);
res.send(popupTools.popupResponse(req.user));
}
);

Missing error handler on `socket` & TypeError: undefined is not a function in node js

i have a little problem here, i want to make simple chat app using nodejs, but in terminal this error was come out, of course in web browser chat app doesn't work, this is my code
// # SimpleServer
//
// A simple chat server using Socket.IO, Express, and Async.
//
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
//set this to your project URL
var c9server = 'http://sne.dlinkddns.com:8080/politan/writeData.php';
//ssl issues in c9
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
//
// ## SimpleServer `SimpleServer(obj)`
//
// Creates a new instance of SimpleServer with the following options:
// * `port` - The HTTP port to listen on. If `process.env.PORT` is set, _it overrides this value_.
//
var router = express();
var server = http.createServer(router);
var io = socketio.listen(server);
router.use(express.static(path.resolve(__dirname, 'client')));
var messages = [];
var sockets = [];
// create connection to file
// var fs = require('fs');
// var writeStream = fs.createWriteStream('log.json');
io.on('connection', function (socket) {
messages.forEach(function (data) {
socket.emit('message', data);
});
sockets.push(socket);
socket.on('disconnect', function () {
sockets.splice(sockets.indexOf(socket), 1);
updateRoster();
});
socket.on('message', function (msg) {
var text = String(msg || '');
if (!text)
return;
var d = new Date();
socket.get('name', function (err, name) {
var data = {
name: name,
text: text,
date: d
};
var trendData = {
date: d,
count: '1'
};
broadcast('message', data);
messages.push(data);
//log data
logData(data, 'messages.json');
logData(trendData, 'trend.json');
//write data to mysql
postData('data='+JSON.stringify(data), c9server);
});
});
socket.on('identify', function (name) {
socket.set('name', String(name || 'Anonymous'), function (err) {
updateRoster();
});
});
});
function updateRoster() {
async.map(
sockets,
function (socket, callback) {
socket.get('name', callback);
},
function (err, names) {
broadcast('roster', names);
}
);
}
function broadcast(event, data) {
sockets.forEach(function (socket) {
socket.emit(event, data);
});
}
function logData(data, file){
//setup file
var fs = require('fs');
//append the new data to the log
fs.appendFile(file, JSON.stringify(data)+"\n", function (err) {
if (err) throw err;
console.log(JSON.stringify(data) +' was appended to file!');
});
}
function postData(data, postUrl){
var request = require('request');
// 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: postUrl,
method: 'POST',
headers: headers,
form: data
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log(body)
} else {
console.log(error);
}
})
}
// server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
server.listen(8081, process.env.IP, function(){
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
The error in console
Missing error handler on `socket`.
TypeError: undefined is not a function
at Socket.<anonymous> (/var/www/html/politan/server.js:89:14)
at Socket.emit (events.js:107:17)
at Socket.onevent (/var/www/html/politan/node_modules/socket.io/lib/socket.js:335:8)
at Socket.onpacket (/var/www/html/politan/node_modules/socket.io/lib/socket.js:295:12)
at Client.ondecoded (/var/www/html/politan/node_modules/socket.io/lib/client.js:193:14)
at Decoder.Emitter.emit (/var/www/html/politan/node_modules/component-emitter/index.js:134:20)
at Decoder.add (/var/www/html/politan/node_modules/socket.io-parser/index.js:247:12)
at Client.ondata (/var/www/html/politan/node_modules/socket.io/lib/client.js:175:18)
at Socket.emit (events.js:107:17)
at Socket.onPacket (/var/www/html/politan/node_modules/engine.io/lib/socket.js:101:14)
Glad if you can help my little project, thanks

Access all users from REST API call?

The API call only allows me to get only 1000 users at a time. However, I know I have 9800 users. I can pass in a parameter in the url where to start and maximum results(limited to 1000). But I need to fetch them all and don't know how to go about it.
I am using Node. And Bluebird and Request NPM modules.
Here is my code
/********************** MODULES/DEPENDENCIES **********************/
var express = require('express');
var request = require('request');
var Promise = require('bluebird');
var _ = require("lodash");
/********************** INITIATE APP **********************/
var app = express();
console.log("Starting node server...");
/**
* #param url - The url to GET
* HTTPS GET Request Function
* #return Promise - Promise containing the JSON response.
*/
/********************** URL GET FUNCTION **********************/
function get(url) {
return new Promise(function(resolve, reject) {
// var auth = "Basic " + new Buffer(username + ':' + password).toString("base64");
var options = {
url: url,
headers: {
// 'Authorization': auth,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
};
console.log("Calling GET: ", url);
if ('development' == app.get('env')) {
console.log("Rejecting node tls");
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
}
request(options, function(error, response, body) {
if (error) {
reject(error);
} else {
// console.log("This is body: ", body.length);
resolve(body);
}
});
});
};
/********************** HTTPS GET SRERVER DATA **********************/
function getServerData() {
/********************** URL VARIABLES **********************/
var username = 'username',
password = 'password',
role = 'Read-Only',
url_host = 'https://link.com:1000';
/********************** URL 1 **********************/
var url1 = url_host + '/type/PropertySetClasses/SystemObject/Server/?username=' + username + '&password=' + password + '&role=' + role;
// firstResult=9500&maxResults=1&
console.log("Getting server data...", url1);
/********************** GET REQUEST 1 **********************/
return get(url1)
.then(function(res) {
console.log("Got response!");
/********************** FETCH URI FROM RES NESTED OBJECT **********************/
res = JSON.parse(res);
res = res.PropertySetClassChildrenResponse.PropertySetClassChildren.PropertySetInstances.Elements;
// console.log("This is res 1: ", res);
var server_ids = _.map(res, function(server) {
return server.uri;
});
console.log("Calling server urls", server_ids);
/********************** RETURN URL WITH SERVER URI **********************/
return Promise.map(server_ids, function (id) {
var url2 = url_host + id + '?username=' + username + '&password=' + password + '&role=' + role;
console.log("Calling URL", url2);
/********************** RETURN SERVER PROPERTIES **********************/
return get(url2)
.then(function(res2) {
res2 = JSON.parse(res2);
var elements = res2.PropertySetInstanceResponse.PropertySetInstance.PropertyValues.Elements;
console.log("Got second response", res2, elements);
return elements;
});
})
.then(function (allUrls) {
console.log("Got all URLS", allUrls);
return allUrls;
});
})
.catch(function(err) {
console.error(err);
throw err;
});
};
/********************** PORT HANDLER **********************/
app.listen(8080, function() {
console.log("Server listening and booted on: " + 8080);
/********************** ROUTER **********************/
app.get("/serverInfo", function (req, res) {
console.log("Calling server info");
/********************** RETURN PROMISE **********************/
return getServerData()
.then(function(userData) {
var userData = JSON.stringify(userData, null, "\t");
console.log("This is USERDATA Data: ", userData);
res.send(userData);
})
.catch(function(err) {
console.error(err);
res.send({
__error: err,
message: err.message
});
});
});
});

Categories

Resources