I cannot connect to Splunk with the Javascript but can with Java - javascript

I am trying to connect to Splunk with the Javascript. I am already connecting with the Java am able to do anything that I want. When I try to connect with Javascript I keep getting a 401. I am using the same credentials for both Java and Javascript, so I know there is no issue there. My code is directly out of the examples. Here it is:
exports.main = function(opts, done) {
// This is just for testing - ignore it
opts = opts || {};
var username = opts.username || "username";
var password = opts.password || "password";
var scheme = opts.scheme || "https";
var host = opts.host || "domain.com";
var port = opts.port || "8089";
var version = opts.version || "5";
var service = new splunkjs.Service({
username: "username",
password: "password",
scheme: "https",
host: "domain.com",
port: "8089",
version: "5"
});
// First, we log in
service.login(function(err, success) {
// We check for both errors in the connection as well
// as if the login itself failed.
if (err || !success) {
console.log("Error in logging in");
console.log(err);
done(err || "Login failed");
return;
}
// Now that we're logged in, let's get a listing of all the saved searches.
service.savedSearches().fetch(function(err, searches) {
if (err) {
console.log("There was an error retrieving the list of saved searches:", err);
done(err);
return;
}
var searchList = searches.list();
console.log("Saved searches:");
for(var i = 0; i < searchList.length; i++) {
var search = searchList[i];
console.log(" Search " + i + ": " + search.name);
console.log(" " + search.properties().search);
}
done();
});
});
};
if (module === require.main) {
exports.main({}, function() {});
}
Here is the error message:
There was an error retrieving the list of saved searches: { response:
{ headers:
{ connection: 'close',
'content-length': '100',
'content-type': 'text/xml; charset=utf-8',
date: 'Tue, 20 Nov 2012 22:27:11 GMT',
server: 'Splunkd' },
statusCode: 401 },
status: 401,
data: '<response>\n<messages>\n<msg type="WARN">call not properly authenticated</msg>\n</messages>\n</response>',
error: null }
I run this on the command line with Node and get the 401 error. What else do I need to check to see what I am doing wrong.

Cross origin policy no doubt CORS

Cross-Origin policy is definitely something you want to look out as you start getting into more advanced use cases with the SDK but looking at your sample code, it looks like you unintentionally put double quotes around the variable names when instantiating the service object.
I copied your code, replaced the variable values to my server, removed the double quotes second time around and verified it through command line using node ... it worked just fine.

Related

How do I send error message from server to client?

I'm making some requests from my express server, and I'm wondering how I can pass an error message to the client side. I want to be able to see the error message when I console log from the client as well as from the server, but I'm not sure how to relay this message back to the client to make that possible.
Here is an example of a request from my server.js file
app.get('/assign*', (request, response) => {
var baseurl = 'https://OURACC.nocrm.io/api/v2/'
var apikey = crmkey;
var pathname = request.url; // retrieves the requested pathname (ie, /crm/path)
pathname = pathname.split('?');
pathname = pathname[0].split('/')
var parameters = request.query.params;
var path = pathname[2]; // gets request path for the crm
var lead_id = parameters.lead_id
var user_id = parameters.user_id
var params = {
user_id: user_id
}
if(path === 'leads'){
axios.post(baseurl + path + '/' + lead_id + '/assign',
params
,{
headers: {'X-API-KEY': apikey, content_type: "json", accept: "application/json"}
}).then(function(res){
response.send(res.data);
}).catch(function(error){
console.log("ERROR in /assign/leads/{id}/assign" + error);
})
}
})
This is what the call to this request looks like client side
$.get('/assign/leads', {params: data}).then(response => {
console.log(response);
}).catch(error => {
console.log(error);
})
I've tried this server side
response.send(error)
but this doesn't return me anything client side like I was expecting.
I'm sure this is something simple, but I couldn't find much online about it, thanks.
If I read your code correctly, just put response.send(yourErrorMessage) in the catch block
You have to specify response code. For example:
res.status(400);
res.send('None shall pass');

npm package simple-oauth2 404 not found

I have a weird bug going on with my code.
I'm using the simple-oauth2 library (https://github.com/lelylan/simple-oauth2) and my code works fine on Windows.
When I try to run my code on a linux server (raspberry pi zero), the oauth library keeps on returning 404 Not Found for my oauth request (specifically "Access Token Error Not Found" as per the code below).
What's going on?
Code (working with Yelp API):
var fs = require('fs');
var cID = fs.readFileSync('blahblahblah', 'utf8');
var cSecret = fs.readFileSync('blahblahblah2', 'utf8');
var credentials = {
client: {
id: cID,
secret: cSecret
},
auth: {
tokenHost: 'https://api.yelp.com',
tokenPath: '/oauth2/token'
}
};
var oauth2 = require('simple-oauth2').create(credentials);
var tokenConfig = {};
module.exports.gimmeMuhToken = function(cb) {
oauth2.clientCredentials.getToken(tokenConfig, function(error, result) {
if (error) {
return console.log('Access Token Error', error.message);
}
cb(oauth2.accessToken.create(result).token.access_token); // Return the token
});
};
Thanks
Found the culprit.
It was line endings...

Unable to connect with SQL Server using Node.js

I have created an application using Node.js to connect with SQL Server. Below is the code:
app.get('/SalesStatistics', function (req, res) {
var Connection = require('tedious').Connection;
// config for your database
var config = {
user: "****",
password: "*****",
server: "abc",
database: "xyz"
};
var connection = new Connection(config);
connection.on('connect', function (err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement();
});
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatement() {
request = new Request("select * from employee;", function (err) {
if (err) {
console.log(err);
}
});
var result = "";
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
result += column.value + " ";
}
});
console.log(result);
result = "";
});
request.on('done', function (rowCount, more) {
console.log(rowCount + ' rows returned');
});
connection.execSql(request);
}
});
Received the below error in console:
message: 'Requests can only be made in the LoggedIn state, not the Connecting state'
code: EIINVALIDSTATE
Also tried the sample from Github site, but still I could not connect to SQL Server. Please let me know if any other possibility.
I just encountered the same problem awhile ago running the same code above with similar environment.
It turn out that I did not configure the sql server (using Sql Server Management Manager) to accept TCP connection to port (1433). After I done that, everything work fine.

REST API node.js

I am trying to retrieve data from a REST API in the server side (.js) and display it in my view (.jade)
I was able to get the data but was not able to send it to the view .
This is how my code looks like :
var BugData ='initial data' ;
var https = require('https');
var optionsget = {
rejectUnauthorized: false,
host : 'My host', // here only the domain name
// (no http/https !)
port : 443,
path : 'Mypath', // the rest of the url with parameters if needed
method : 'GET' // do GET
};
console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');
// do the GET request
var reqGet = https.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
res.on('data', function(d) {
console.info('GET result:\n');
BugData =d;
console.log('Show Data : ***** \n' +d);
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
res.render('index', { ab:BugData});
BugData (was defined before )is the variable i am trying to send to the view but for some reasons it is empty and does not contain the variable 'd'
Does anyone know why or how can i solve this ?
Thanks
There is no need to write that long code.
Be simple, follow these steps:
1) install request package:
npm install --save request
2) outside of router add:
var request = require('request');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
3) use this code inside router:
request.get({url: 'https://my-host/Mypath'}, function(err, response, body) {
var data = {};
if (err) {
console.error(err);
data.err = err;
}
data.ab = body;
console.log('Data: ', data);
res.render('index', data);
});

Node.js (Openshift) express response not working

I am using OpenShift and Node.js
I am trying to get the average - rating for each result but I cant
get the response to work even though the console reports correctly.
I get 3.9454323 into the console , but when I git localhost:3002/getM/1 the response is blank.
app.get('/getM/:movieId', function(request,response) {
var movieId = request.params.movieId;
var connection = mysql.createConnection({
host: process.env.OPENSHIFT_MYSQL_DB_HOST || 'localhost',
user: process.env.OPENSHIFT_MYSQL_DB_USERNAME || 'root',
password: process.env.OPENSHIFT_MYSQL_DB_PASSWORD || '',
port: process.env.OPENSHIFT_MYSQL_DB_PORT || '3306',
database: 'test'
});
connection.connect(function (err) {
if (err) {
console.error('error connecting: ' + err.stack);
response.send("error connecting to database");
return;
}
console.log('connected as id ' + connection.threadId);
});
connection.query('SELECT * FROM `ratings` WHERE `movieId` = ?',[movieId], function(err, result) {
if (err) {
response.send(err);
}
var sum = 0;
result.forEach(function(movie) {
sum += movie["rating"];
console.log(sum);
});
console.log(sum/result.length);
response.send(sum/result.length);
});
});
You are passing a numeric argument to response.send(). Here's what the express documentation says:
res.send([body])
Sends the HTTP response.
The body parameter can be a Buffer object, a String, an object, or an
Array.
see: http://expressjs.com/api.html
Try this:
response.send( "" + sum/result.length );
EDIT:
BTW, if you're using an older version of express, then express may be trying to interpret the number as an HTTP status code. I'm not sure what express will do with floating point values, but in any case that's clearly not what you intended.
Finally when a Number is given without any of the previously mentioned
bodies, then a response body string is assigned for you. For example
200 will respond will the text “OK”, and 404 “Not Found” and so on.
see: http://expressjs.com/3x/api.html#res.send

Categories

Resources