Node Request inside request with cookie - node.js

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();
});
};

Related

How to do AJAX POST call in express.js file in handlebar?

I am trying to send/update data to mongoDB database via AAJAX call but the command is not reaching theere. I have tried debugging using alert in between the code but the command is not reaching there. Means AJAX call doesn't get executed.
Below is my AJAX POST request code:
var text = "Done";
var data = {
selectedValue: text
}
$ajax({
method: 'POST',
url: '/update-sources',
dataType: 'text/json',
data: data,
success: function(data){
console.log(data);
alert("Working!!")
}
});
And Below is the /update-sources route code:
router.post('/update-sources', function(req, res, next) {
console.log("/Update-Sources")
User.findOneAndUpdate({email: req.user.email}, {$set:{status:data.selectedValue}}, {new: true}, (err, doc) => {
if (err) {
console.log("Something wrong when updating data!");
}
else
{
res.render('taskswriter');
console.log(doc);
return "Great Working!";
}
});
});
What mistake I am doing?
Would be great if you shared browser's console output, but trying to execute attached client-side snippet, I got the following error:
VM219:7 Uncaught ReferenceError: $ajax is not defined
at <anonymous>:7:1
You've got a typo there - it should be $.ajax as you are accessing a function from within jQuery namespace (https://api.jquery.com/jQuery.ajax/)

how to send fetched data node js

Hello i have a request which fetch some json data from third party API:
request({
url: 'https://api.steampowered.com/IEconService/GetTradeOffers/v1/?key=MYAPIKEY&get_sent_offers=1&active_only=1&format=json',
json: true
}, (err, responser, body, undefined) => {
tradeItems = JSON.stringify(body.response['trade_offers_sent'][0].items_to_give);
});
How can i send tradeItems fetched data to offer.addTheirItems value?
client.on('webSession', function(sessionID, cookies) {
manager.setCookies(cookies, function(err) {
if (err) {
console.log(err);
process.exit(1);
return;
}
let offer = manager.createOffer("https://steamcommunity.com/tradeoffer/new/?partner=123456789&token=1234");
offer.addTheirItems();
offer.setMessage("");
offer.send(function(err, status) {
if (err) {
console.log(err);
return;
}
First, that's are javascript's async issue.
The solution is in many ways.
change the request function to async function. and make tradeItems variable to outside from request function.
I recommend request-promise module
move below codes to in upper code's callback function.
This is a simple answer because your sample code is separated into two parts.

softlayer-client: unable to update VPN for User_Customer via REST API

I am experimenting with the softlayer-client api wrapper in my Node Express application. My goal is to update the VPN password of a User_Customer by calling the updateVpnPassword method on a specific user.
I can construct a call to achieve a VPN password update using request, but I'm not sure it's the best way to achieve the desired result.
Can the softlayer-client module be used to make an similar call to this:
function updateVpnPassword(req, res, next) {
// Construct URL to update VPN
myURL = 'https://' + <userIDAdmin> + ':' + <apiKeyAdmin> + '#api.softlayer.com/rest/v3/SoftLayer_User_Customer/' + <softLayerID> + '/updateVpnPassword/' + <newPassword> + '.json';
request.get({url: myURL}, function (error, response, body) {
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', body);
});
next();
}
My initial attempts have been to try variations on this:
function updateVpnPassword(req, res, next) {
// Assuming var client = new SoftLayer();
client
.auth(<userIDAdmin>, <apiKeyAdmin>)
.path('User_Customer', <softLayerID>,'updateVpnPassword')
.parameters(<newPassword>)
.put(function(err,result){
console.log(result);
if (err) {
next(err); // Pass errors to Express.
}
else {
// update successful
}
});
next();
}
But the console log gives an error response like
{ message: { error: 'Internal Error', code: 'SoftLayer_Exception_Public' } }.
I expect a TRUE or FALSE response, to indicate the whether the update is successful.
A similar python client can be found here but I require an implementation in JS.
I'm not familiar with nodejs but I installed the package softlayer-node and run your second code and it worked.
I also created the following script and I got TRUE
var username = 'set me';
var apikey = 'set me';
var userId = 1111111;
var SoftLayer = require('softlayer-node');
var client = new SoftLayer();
client
.auth(username, apikey)
.path('User_Custome', userId, 'updateVpnPassword')
.parameters('P#ssword123')
.put()
.then(function(result) {
console.log(result);
}, function(error) {
console.log(error);
});
node command:
$ node updateVpnPassword.js
true
Did you tried by sending that request using curl or any other REST client like postman?
If you get the same error then I recommend you submit a ticket and provide information like the id of users you are trying to update the vpn password and the user with which you are sending the request.

node.js server and AWS asynchronous call issue

I have a simple node Express app that has a service that makesa call to a node server. The node server makes a call to an AWS web service. The AWS simply lists any S3 buckets it's found and is an asynchronous call. The problem is I don't seem to be able to get the server code to "wait" for the AWS call to return with the JSON data and the function returns undefined.
I've read many, many articles on the web about this including promises, wait-for's etc. but I think I'm not understanding the way these work fully!
This is my first exposer to node and I would be grateful if somebody could point me in the right direction?
Here's some snippets of my code...apologies if it's a bit rough but I've chopped and changed things many times over!
Node Express;
var Httpreq = new XMLHttpRequest(); // a new request
Httpreq.open("GET","http://localhost:3000/listbuckets",false);
Httpreq.send(null);
console.log(Httpreq.responseText);
return Httpreq.responseText;
Node Server
app.get('/listbuckets', function (req, res) {
var bucketData = MyFunction(res,req);
console.log("bucketData: " + bucketData);
});
function MyFunction(res, req) {
var mydata;
var params = {};
res.send('Here are some more buckets!');
var request = s3.listBuckets();
// register a callback event handler
request.on('success', function(response) {
// log the successful data response
console.log(response.data);
mydata = response.data;
});
// send the request
request.
on('success', function(response) {
console.log("Success!");
}).
on('error', function(response) {
console.log("Error!");
}).
on('complete', function() {
console.log("Always!");
}).
send();
return mydata;
}
Use the latest Fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to make HTTP calls. It has built-in support with Promise.
fetch('http://localhost:3000/listbuckets').then(response => {
// do something with the response here
}).catch(error => {
// Error :(
})
I eventually got this working with;
const request = require('request');
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
parseString(body, function (err, result) {
console.log(JSON.stringify(result));
});
// from within the callback, write data to response, essentially returning it.
res.send(body);
}
else {
// console.log(JSON.stringify(response));
}
})

Http request from Node (Express) to Yii2 api endpoint

I have to do request from node to Yii2 api. It doesn't throw any errors, but doesn't return anything either. When I do request to Yii2 api method directly in browser, value is returned. Here is my request in route in node:
router.get('', function (req, res) {
var parameter = 20;
request({
url: 'http://**.**.**.***:8000/web/index.php?r=api/get-value',
parameter: parameter,
method: 'GET'
}, function(error, response, body) {
if(error || response.statusCode != 200)
throw error;
res.send(body);
});
});
module.exports = router;
And here is method/endpoint in Yii2 controllers/apiController.php:
public function actionGetValue($inverterId) {
return $inverterId * 2;
}
Any suggestions what could be wrong/missing?
You can use the following
var http = require('http');
var client = http.createClient(8000, 'localhost');
var request = client.request('GET', '/web/index.php?r=api/get-value');
request.write("stuff");
request.end();
request.on("response", function (response) {
// handle the response
});
Resource Link:
Http request with node?
Sending http request in node.js
or Another full example:
Get requests
Now we’ll set up a super simple test to make sure it’s working. If it’s not still running, run your simple Node server so that it’s listening on http://localhost:8000. In a separate file in the same directory as your http-request.js where your new module lives, add a file called test-http.js with the following contents:
// test-http.js
'use strict';
const
request = require('./http-request'),
config = {
method: 'GET',
hostname: 'localhost',
path: '/',
port: 8000
};
request(config).then(res => {
console.log('success');
console.log(res);
}, err => {
console.log('error');
console.log(err);
});
This will import our module, run a request according to the configured options, and console log either the response, or an error if one is thrown. You can run that file by navigating to its directory in the command line, and typing the following:
$ node test-http.js
You should see the following response:
success
{ data: 'Cake, and grief counseling, will be available at the conclusion of the test.' }
Resource Link:
https://webcake.co/sending-http-requests-from-a-node-application/
Okay, shame on me, I did not check, what's going on in public function beforeAction($action) in apiController.php - since request to endpoint getValue() is done from the "outside", it falls under a condition, that does not allow further actions and returns false - that's why response wasn't changing no matter what was done/set in getValue().

Resources