Unable to make request in node.js - node.js

I am using the following code in the controller by CCAvenue but I get an error
TypeError: request.on is not a function
Below is the code for the request
request.on('data', function (data) {
console.log("data is ----------------> " + data);
body += data;
encRequest = ccav.encrypt(body, workingKey);
console.log("Enc request " + encRequest);
formbody = '<form id="nonseamless" method="post" name="redirect" action="https://secure.ccavenue.com/transaction/transaction.do?command=initiateTransaction"/> <input type="hidden" id="encRequest" name="encRequest" value="' + encRequest + '"><input type="hidden" name="access_code" id="access_code" value="' + accessCode + '"><script language="javascript">document.redirect.submit();</script></form>';
});
request.on('end', function () {
response.writeHeader(200, {
"Content-Type": "text/html"
});
response.write(formbody);
response.end();
});
I am including the request using var request = require('request')
Edit:
request.post("https://secure.ccavenue.com/transaction/transaction.do?command=initiateTransaction", {
form: {
encRequest: encRequest,
access_code: accessCode
}
},
function (error, response, body) {
console.log(body);
});
I get a response in my body which is an html page. How do I send it back to the browser in sail.js framework ?
Edit 2 :
I've tried using sails.request method too but there is no response.
var payReq = {
url: "https://secure.ccavenue.com/transaction/transaction.do?command=initiateTransaction",
method: "POST",
headers: {
"Content-Type": "text/html"
// "Content-Type": 'application/json'
},
// data : {
// encRequest: encRequest,
// access_code: accessCode
// }
data : `encRequest=${encRequest}&access_code=${accessCode}`
}
sails.request(payReq);

I think you're using Request in an incorrect way.. this pattern you're using would work for the HTTP/HTTPS libraries. Here's a Request example.
var request = require('request');
var options = {
url: "https://httpbin.org/ip",
method: "get"
};
console.log('Requesting IP..');
request(options, function (error, response, body) {
if (error) {
console.error('error:', error);
} else {
console.log('Response: Headers:', response && response.headers);
}
});
The request.on('data' .. pattern is used by the Native HTTP and HTTPs libraries. examples would be here:
https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html
This page includes examples using Request, HTTP, Axios.

Related

Node.js 3rd party REST API call

Im using nodejs to make a call to a 3rd party API. My code code returns the correct data for an id that I'm passing in my backend. When I run my app, to retrieve the data I go to localhost:5000/api/Dls.
My code
app.get("/api/Dls", (req, res) => {
const response = {
success: false
};
if (req.user && Authorized.myToken) {
response.success = true;
response.data = {};
response.data.user = req.user;
const id = response.data.user.sub;
var options = {
method: 'GET',
url: 'https://someApi/byId/' + 'id',
headers:
{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
}
};
request(options, function (error, response, body){
if (error) {
console.log(error);
return;
}
const data = response.body;
const userDls = JSON.parse(data)
return res.json(userDls);
});
}
});
Now I'm trying to do something like this localhost:5000/api/Dls/1234 instead of using a hard coded id in the backend
I attempted doing the following but when I enter a valid id in the url (ex. localhost:5000/api/Dls/1234) I get this "", any idea to what I should be doing?
app.get("/api/Dls/:id", (req, res) => {
const response = {
success: false
};
if (Authorized.myToken) {
response.success = true;
var options = {
method: 'GET',
url: 'https://someApi/byId/',
headers:
{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
}
};
request(options, function (error, response, body){
if (error) {
console.log(error);
return;
}
const data = response.body;
const userDls = JSON.parse(data)
return res.json(userDls);
});
}
});
Any feedback would be appreciated!
You are not passing the route id to the api.
response.success = true;
var options = {
method: 'GET',
url: 'https://someApi/byId/' + req.params.id,
headers:{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
}
};

Why i am getting unable to open document error or blank pdf in opening a pdf on client side?

I am hitting a get api in react similar to http://www.orimi.com/pdf-test.pdf which needs some secret information which is available only at middleware written in node. I want to open the pdf on client side(browser). So I am hitting the proxy get api which will hit the middleware and middleware will hit the backend server, but I am getting unable to open document and blank pdf. Can anyone tell me what is wrong with this code?
fetch(pdfApiMiddlewareUrl, {
method: "GET",
headers: {
"Content-Type": "application/pdf",
'Content-Disposition': 'inline; filename=your_file_name'
},
responseType : 'blob'
})
.then(res => res.blob())
.then(response => {
var blobUrl = URL.createObjectURL(response);
window.open(blobUrl);
})
.catch(error => {
console.log("HEREEEEEEEE");
console.log(error);
});
MIDDLEWARE CODE:
var urlEndPointsToHit = decodeURIComponent(req.query.urlToHit);
var url = urlEndPointsToHit+'?secret='+secretInfo;
var options;
options = {
url: url,
method: 'GET',
headers: {
'Content-type': 'application/pdf'
},
};
if(options) {
options.qs = req.query || {};
}
request(options, function(err, resp, body) {
req.locals = body;
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Cache-Control', 'no-cache');
next();
});

Node JS Request Printing nothing in console

I'm making an post call using the nodejs requests module. However, the console.log statements seems to be not working for either the error or the response.body that I am trying to get.
My POST request needs the following headers -
Accept : "application/json"
Content-Type : "application/json"
Authorization : Basic + Base64Encoded(username+password)
The post body is something like this
Body:
{
"arg_1" : "a_string_key"
, "arg_2" : "a_string"
, "arg_3" : "a_string"
, "arg_4" : "some_value"
, "arg_5" : "some_string"
, "arg_6" : "<yyyy-mm-dd>"
, "arg_7" : "<yyyy-mm-dd>"
}
My code does nothing but send a POST request and checks if the response.statusCode ==200
Here is what I am doing
var int_user = "username";
var int_pass = "password";
var encoding = "base64"
var auth = "Basic" + new Buffer(int_user + int_pass).toString(encoding);
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": auth
}
var options = {
url: 'URL_I_WANT',
// method: 'POST',
headers: headers,
body : {
"arg_1": "a_string_key",
"arg_2": "a_string",
"arg_3": "a_string",
"arg_4": "some_value",
"arg_5": "some_string",
"arg_6": "<yyyy-mm-dd>",
"arg_7": "<yyyy-mm-dd>"
},
json: true
}
console.log('Before request');
request.post(options, function(error, response) {
if (error) {
console.log(error);
}
try {
if (!error && response.statusCode == 200) {
console.log(response.body);
console.log('Success');
}
} catch (error) {
console.log(error)
}
});
console.log('After request');
The code runs without any glitch and I get the before and after request console statements. However the statements inside the requests do not appear in the console, which means my request is not going through. I am not able to understand this. Shouldn't an error come if there is an issue with the request itself? Any if the request is failing, why isn't the error printed out?
This could be because your node process is auto-closed and it will exit before the async request to finishes (haven't looked into it but it might be something configurable). I've seen such set-up on repl.it for example.
To overcome this(if not configurable), you could wrap your code in an async function and use the request-promise to call await request.
var request = require('request-promise-native');
var int_user = "username";
var int_pass = "password";
var encoding = "base64"
var auth = "Basic" + new Buffer(int_user + int_pass).toString(encoding);
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": auth
}
var options = {
url: 'https://google.com',
method: 'POST',
headers: headers,
body : {
"arg_1": "a_string_key",
"arg_2": "a_string",
"arg_3": "a_string",
"arg_4": "some_value",
"arg_5": "some_string",
"arg_6": "<yyyy-mm-dd>",
"arg_7": "<yyyy-mm-dd>"
},
json: true
};
console.log('Before request');
async function main() {
try {
const response = await request.post(options);
if (response.statusCode === 200) {
console.log(response.body);
console.log('Success');
process.exit();
}
console.log(`Bad statusCode:${response.statusCode}`);
}
catch (error) {
console.log(error);
}
}
main();
you can check-out the code below
a link to the code above, working on repl.it

POST Requests not working using request module in node.js

I want to send data to the java back end which is run on tomcat server.this is what i have tried so far.i have already installed request module.get method is working properly.
Router.post('/', function(req, res) {
request({
uri: "http://localhost:8080/HIS_API/rest/UserService/registerUser",
method: "POST",
form: {
roleId:2,
employeeId:26,
userName:"testing",
password:"123"
}
}, function(error, response, body) {
console.log(body);
});
});
You have to use JSON.stringify to send data like in this format. before that write console.log(error). and check what's the error you are getting.
request({
url: url, //URL to hit
method: 'post',
headers: { "Authorization": req.headers.authorization},//if required
timeout: 60 * 1000,
body: JSON.stringify(body)
}, function (error, result, body) {
if (error) {
console.log(error);
} else if (result.statusCode === 500) {
console.log('error');
} else {
console.log(body);
}
});

oAuth code exchange for secret token

I'm making an app that is supposed to use oAuth to authenticate players from the Blizzard servers, I want to access their character info.. and I can't figure out how to ask for the secret_token. I guess I'm doing my post request wrong below is the code I'm using
app.post('/', function(req, res) {
var code = req.body.code; //this is the code i get ounce the player is redirected back to my redirect_uri
var redirectUri = "https://localhost:3000/oauth_callback.html";
var scope = "wow.profile";
var key = "they client_id i was given";
var secret = "they secret I was given";
var grantType = "authorization_code";
var tokenUri = "https://us.battle.net/oauth/token";
var uriBody = "?client_id=" + key + "&client_secret=" + secret + "&grant_type=authorization_code&code=" + code + "&redirect_uri=" + redirectUri + "&scope=" + scope;
request({
url: tokenUri, //URL to hit
method: 'POST',
headers: {
'Content-Type': "application/x-www-form-urlencoded",
},
body: uriBody //Set the body as a string
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
so basically I'm getting the code making a post request to my server with it, and then triggering a post request to the blizzard server trying to exchange my code for an access token.
The error I get is:
401 '{"error":"unauthorized","error_description":"An Authentication object was not found in the SecurityContext"}'
I'm using Node.js & request.js to make the post, my guess is I'm not making a proper request post request?
I think body key is not acceptable in request.
Send data in json if content-type is JSON or form if content-type is x-www-form-urlencoded
Like this
request({
url: tokenUri, //URL to hit
method: 'POST',
headers: {
'Content-Type': "application/x-www-form-urlencoded",
},
form: uriBody //Set the body as a string
}, function(error, response, body){
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
finally! here is how I got it to work!
qs = query-string.js library...
var token_params = qs.stringify({
client_id: key,
client_secret: secret,
code: code,
scope: scope,
grant_type: 'authorization_code',
redirect_uri: redirectUri
});
request('https://us.battle.net/oauth/token?' + token_params, function(error, response, body){
if (error) {
console.log(error);
} else {
console.log(body)
}
});

Resources