calling jasper report rest api through node js - node.js

I am very much new to the concept of jasper report. My team had already build some reports in jasperserver. the only thing I needed is to call reports. From a node server. I tried code from Jasper Rest API, run a report
router.get('/', function(req, res, next) {
request.post({url: "http://localhost:3030/jasperserver/rest/login",
qs: {j_username: "jasperadmin", j_password: "jasperadmin"}},
function(err, res, body) {
if(err) {
return console.error(err);
}
else{
request.get("http://localhost:3030/jasperserver/rest_v2/reports/SampleQueryReport.pdf",
function (error, response, body1) {
if (!error) {
console.log("downloading")
}
else{
console.log(response.statusCode);
console.log(error);
}
})
}
});
});
I want to get the report in pdf format. But when I tried this code am getting 401 unauthorized error.
I am using express js,node js,
npm module request, which I globally declared in app.js.
But I can log to the jasper soft directly with this credentials through url.

I understood what the problem was. It shows unauthorized error because in the second request it has no cookie. That is in the first request login take place and a cookie is generated. Which is not passed in the second request. So when I passed cookie with that request it worked. My mistake.

Related

stopping postman after request is done

I am trying to create a Weather API using node. In my controller file, I have this code which is run for the /check route.
controller.js:
//Check Weather
exports.check = (req, res) => {
UserModel.check(req.body.city)
};
model.js:
//Check Weather
function getData(city) {
url = "something";
request(url, function (err, response, body) {
if(err){
console.log('error:', error);
} else {
console.log('body:', body);
}
});
}
exports.check = (city) => {
city = city.toLowerCase();
let values = getData(city);
console.log(city);
return(values);
};
route:
app.post('/check', [
UsersController.check
]);
When I run this, it functions properly and the correct thing is logged in the console. However, after I send a request in Postman and the console.log shows up, Postman seems to be hung up as seen in this pic. Is there anyway I can make it so that Postman stops sending the request after return or console.log?
Postman is waiting for a response from the server. Your code is not currently sending any response, so postman seems 'hung up' as it is waiting. Try changing the line saying UserModel.check(req.body.city) to say res.send(UserModel.check(req.body.city)) so it will send the data returned from your UserModel.check function back as the response. Alternatively, if you don't want to send back the returned value, you could just add res.send(PutWhateverYouWantSentHere) after the function call.

microservice with node and needle

I'm trying to make my monolithic application written in node and express to a microservice application in node, needle(to communicate between microservices) and express. My architecture is as follows,
I have a microservice called gateway_service to handle all the requests from frontend UI
I have another microservice called users_service to handle requests related to users, users_service uses passport local strategy to manage sessions and this session id is sent as a cookie by passport
When I try to change my application to microservice I'm doing the following
Whenever I receive a request from my client say, postman in gateway_service I can see the cookie coming through header, and I'm able to pass it to user_service by setting headers option as mentioned in needle.
How to send the cookie that I receive from user_service to the postman back to he can save the cookie(in case of first hit)??
I'm adding a small code snippet, hoping it will help?
Am I doing it in the right way??
when I'm doing as shown below Im getting the error "Cannot set headers after they are sent to the client"
function (req, res, next) {
var options = {
headers: req.headers,
parse_cookies:true
}
needle.post(url + "login", req.body, options, function (error, response, body) {
if (!error) {
res.writeHead(response.statusCode,response.headers);
res.send(body)
console.log(res);
next();
} else {
console.log("error in info from users micro service");
res.send(error);
next();
}
});
},

Node Request inside request with cookie

I am using node request var request = require(“request”); in my config node to do a POST request and in response get a Cookie which need to be referred in all rest of requests.
I tried enabling COOKIE JAR that works fine if i chain my request under first request but I want to call rest of requests like GetList from custom node.
I tried toughcookie (file cookie) not working when i add var j = request.jar(new FileCookieStore(‘cookies.json’));
node stop working with no error.
Below is my config node, code using which I am getting Cookie.
function myAuthNode(n) {
RED.nodes.createNode(this,n);
this.username=n.username;
this.password=n.password;
this.connect=function(){
//TODO-NG need to make URL configurable
request.post({url: "http://localhost:8080/api/method/login", qs: {usr: this.username, pwd: this.password}}, function(err, res, body) {
if(err) {
return console.error(err);
}
console.log("HERE IF I PUT REQUEST Works fine");
console.log("CAN WE PASS ANOTHER REQUEST here from calling SOURCE to execute here?");
});
};
}
Here in this custom node I am calling
// The main node definition - most things happen in here
function GetListNode(n) {
// Create a RED node
RED.nodes.createNode(this,n);
console.log('I am called');
//using auth config now you are connected, tell me what is needed?
this.authConfig=RED.nodes.getNode(n.auth);
//connect to config and do auth
this.authConfig.connect();
//THIS ALWAYS FAILS due to cookie not found where as I enable request JAR
request.get({url: "http://localhost:8080/api/resource/Project"}, function(err, res, body) {
if(err) {
return console.error(err);
}
console.log("Response body:", body);
});
}
Please suggest how to handle cookie in request so that all requests after auth works fine?
Can we pass a request definition to another request for execution inside it or how Cookie can be handled ?
I resolved this by doing below inside GetListNode(), i shifted second request inside the call:
this.authConfig.connect(function(){request.get({url: "http://localhost:8080/api/resource/Project"}, function(err, res, body) {
if(err) {
return console.error(err);
}
console.log("Response body:", body);
});});
and inside config node i did below, added a function parameter and called that passed function, WORKED fine :):
this.connect=function(f){
//TODO-NG need to make URL configurable
request.post({url: "http://localhost:8080/api/method/login", qs: {usr: this.username, pwd: this.password}}, function(err, res, body) {
if(err) {
return console.error(err);
}
f.call();
});
};

"Error: Can't set headers after they are sent" in Express app with Node

I am new to Express and Node, and when testing a protected REST endpoint in my app using Advanced REST Client the data is returned from the endpoint to the Client as expected, however the console logs
"Error: Can't set headers after they are sent"
which stops the server. Searching here on SO, this seems to occur when sending more than one response but I don't see that in my code:
router.get('/books', userAuthenticated, function (req, res, next) {
Book.find({}, function(err, docs){
if(err) {
res.send(err)
} else {
res.send(docs);
// next();
// return;
}
})
});
Is this error expected when sending a request/response to/from the Client or am I missing something in handling the error on the server?
Express is a node.js server that features a concept called "middleware", where multiple layers of code get a chance to operate on a request.
In that case, not only do you need to check that your function is not sending back a response twice, but you have to check that other middleware are not sending back a response as well.
In your case, the code indicates that middleware called "userAuthenticated" is being invoked before this function. You should check if that middleware is already sending a response.
I don't think the problem was in the middleware. It looks like I was calling done() twice in passport deserialize. I commented out the first instance and the problem disappeared in all my routes. Although, I am not sure if I should comment out the first or second instance but I'll work on that next.
passport.deserializeUser(function(obj, done) {
console.log(obj);
Account.findById(obj, function(err, user) {
console.log(user);
//done(err, user);
});
return done(null, obj);
});

Connecting to a PHP website with Node.js and keep session

I'm making a testbench with Test'em and Mocha (that run on node.js) in order to test a PHP website.
What I want is to request some URL (e.g http://www.my-website/test.php) and get the http status code as well as the content returned.
I'm doing it with the node.js Request module.
The problem is:
I need to be authenticated to access this page, otherwise I'm
redirected to the login page.
So, does it exist a way to log in my application through Node.js and keep the session open to be able to chain tests on any pages I want?
I was thinking on get the PHPSESSID on login request if it is possible. Do you thing it is a good direction ?
Any help would be much appreciated.
Thank you, have a nice day :)
Michaël
If you set jar: true in your options or use your own custom cookie jar, then request will remember cookies set by the server so that you can keep your session between requests.
mscdex thanks for your answer! But unfortunately it did not work for me :/
hyubs thanks to you too.
Finally I carried on to use Mocha + Request.
Basically what I did is:
Connect through a POST request to the login page and get the PHPSESSID cookie that is returned in the response header.
Pass the cookie in the header in the next requests that target a URL where you have to be logged.
Here is my code :
var params = {
email: 'your_username',
password: 'your_password'
};
var paramsString = JSON.stringify(params);
// Login to the application
request.post('http://localhost/biings/front-end/rest/auth',
{
headers: {
"Content-Type" : "application/json",
'Content-Length' : paramsString.length
},
body: paramsString,
},function (error, response, body) {
// get the PHPSESSID (the last one) that is returned in the header. Sometimes more than one is returned
var sessionCookie = response.headers['set-cookie'][response.headers['set-cookie'].length - 1];
sessionCookie = sessionCookie.split(';');
sessionCookie = sessionCookie[0];
// Write it in a file (this is a quick trick to access it globally)
// e.g.: PHPSESSID=ao9a1j0timv9nmuj2ntt363d92 (write it simply as a string)
fs.writeFile('sessionCookie.txt', sessionCookie, function (err)
{
if(err)
{
return console.log(err);
}
});
});
// don't care about this it() function (it's for Mocha)
it("test 1", function(done)
{
// Get the cookie
fs.readFile('sessionCookie.txt','utf8', function (err, data)
{
if(err)
{
throw err;
}
else
{
// Launch a request that includes the cookie in the header
request.get('http://localhost/biings/front-end/rest/group',
{
headers: {"Cookie" : data},
}, function (error, response, body) {
// Check your request reaches the right page
expect(response.statusCode).equals(200);
console.log(body);
done();
});
}
});
});
It works like a charm for me.
Tell me if you see something wrong or which could be optimized :)
Michaël
Instead of using the request module, use headless browsers like PhantomJS and zombie.js. You can even emulate user interaction with these.

Resources