node.js + request => response showing junk response - node.js

I am using the node.js + request for send HTTP request to URL. I required the JSON response, but I get junk character.
Here is my node.js code
var request = require('request');
var post_data = { UserName: "xxxxx", Password: "xxxxx" };
var post_options = {
url: 'http://xxxxxxx.info/api/CoreUser/cognitoLogin',
method: 'POST',
form: post_data,
headers: {
'AppID': 'zNiphaJww8e4qYEwJ96g555HTAAbAXdj',
'OAuth': 'xxxxxxxxxxxxxxxxxx',
//'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/json;charset=UTF-8',
}
};
// Set up the request
request(post_options, function (error, response, body) {
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
console.log("200");
console.log(response);
}
});
But I received response in junk characters.
I need result in jSON format, What is wrong in this request?

I found the issue, reason is that API response send in gZip format. Here is the change we have to made here. Just enable gzip: true that resolve the things.
var request = require('request');
var post_data = { UserName: "xxxxx", Password: "xxxxx" };
var post_options = {
url: 'http://xxxxxxx.info/api/CoreUser/cognitoLogin',
method: 'POST',
gzip: true,
form: post_data,
headers: {
'AppID': 'zNiphaJww8e4qYEwJ96g555HTAAbAXdj',
'OAuth': 'xxxxxxxxxxxxxxxxxx',
//'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/json;charset=UTF-8',
}
};
// Set up the request
request(post_options, function (error, response, body) {
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
console.log("200");
console.log(response);
}
});

You are missing { json: true } in request call
request(post_options, { json: true }, function (error, response, body) {
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
console.log("200");
console.log(response);
}
});

Related

Getting error "Image file or image_id string must be include", Am i missing something? ETSY Image Upload

Trying to upload Listing image using ETSY Listing Image API
I am fetching "image_id" & "image" from front-end part.
var request = require("request");
var options = { method: 'POST',
url: 'https://openapi.etsy.com/v2/listings/724108136/images',
qs: { oauth_consumer_key: '*********************',
oauth_token: '****************',
oauth_signature_method: 'HMAC-SHA1',
oauth_timestamp: '**********',
oauth_nonce: '*************',
oauth_version: '1.0',
oauth_signature: '*********************'
},
headers:{
'Content-Type': 'multipart/form-data'
},
encoding: null,
responseType: 'buffer',
data:{
image_id:req.body.image_id,
image:req.files.image
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body) // Image file or image_id string must be included
});
I think that there is a few things wrong with this.
It looks like you're passing the OAuth info via in the querystring and not in the headers.
You might want to bump up your request version. I have confirmed this is working with "request": "^2.88.2",
`
const request = require("request");
let options = {
'method': 'POST',
'url': 'https://openapi.etsy.com/v2/listings/724108136/images',
'headers': {
'Authorization': 'OAuth oauth_consumer_key="********",oauth_token="***********",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1585021862",oauth_nonce="*******",oauth_version="1.0",oauth_signature="********"',
'Content-Type': 'multipart/form-data'
},
formData: {
'image': {
'value': fs.createReadStream('./temp/abc123.jpg'),
'options': {
'filename': 'my-shirt.jpg',
'contentType': null
}
}
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body)
});
`

Facebook Messenger: How to send multiple messages with nodejs

I just want to send a messages to all the subscribers with nodejs.
This is my code ( I have hidden the PSID below ):
app.get('/helloguys', function (req, res) {
var messageData = {
batch: [
{recipient: {id: "..."}},{recipient: {id: "..."}}
],
message: {
text: "Hi guys :)",
metadata: "DEVELOPER_DEFINED_METADATA"
}
};
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: token },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Ok", response.statusCode);
} else {
console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
}
});
res.send('Hi :)')
})
I get this in the nodejs console:
Ok 200
but users don't receive the message.
Why ?
EDIT for Lix:
body:
2017-10-18T13:38:43.538998+00:00 app[web.1]: [ { code: 400,
2017-10-18T13:38:43.538999+00:00 app[web.1]: headers: [Object],
2017-10-18T13:38:43.538999+00:00 app[web.1]: body: '{"error":{"message":"Unsupported get request. Please read the Graph API documentation at https:\\/\\/developers.facebook.com\\/docs\\/graph-api","type":"GraphMethodException","code":100,"error_subcode":33,"fbtrace_id":"Dd6+kHN7Tl+"}}' },
EDIT for CBroe:
var messageData = {
batch: [
{method:"POST", message: "Hello", recipient: {id: "1552389158161227"}},{method:"POST", message: "Hello", recipient: {id: "1419003191530571"}}
]
};
It doesn't work
EDIT for CBroe 2:
app.get('/helloguys', function (req, res) {
var batch = [
{method:"POST", body: "message=Test status update&recipient=..."},
{method:"POST", body: "message=Test status update&recipient=..."}
];
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: token },
method: 'POST',
json: batch
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("ok", response.statusCode, response.statusMessage, response);
res.send('hi')
} else {
console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
}
});
})
And now I get:
2017-10-18T15:36:05.981999+00:00 app[web.1]: Failed calling Send API 400 Bad Request { message: '(#100) The parameter recipient is required',
2017-10-18T15:36:05.982009+00:00 app[web.1]: type: 'OAuthException',
2017-10-18T15:36:05.982010+00:00 app[web.1]: code: 100,
2017-10-18T15:36:05.982011+00:00 app[web.1]: fbtrace_id: 'EJLQgP9UoMT' }
As per FB dev docs (they stated somewhere within the docs, and not very obvious)
Note the URLEncoding for the body param
Also, multiple POST requests (batched requests):
While GET and DELETE operations must only have a relative_url and a method field, POST and PUT operations may contain an optional body field.
And >>
This should be formatted as a raw HTTP POST body string, similar to a URL query string.
Also, this type of request should be made as multipart/form-data.
Then, batch request requirements are:
(1) to be multipart/form-data;
(2) consist of URLEncoding strings in 'body' parameter;
(3) batch request should be raw HTTP POST body string.
Node.js request module could send form-data (through form-data module). See docs
So, your code should be like this >>
app.get('/helloguys', function (req, res) {
var batchUrl = 'https://graph.facebook.com';
var r = request.post(batchUrl, function(error, response, body) {
if (error) {return console.log("error\n", error)};
console.log("successfull\n", body) //but fb sends error in body message, so check body.error for any errors
});
var form = r.form();
var multipleMessages = [];
var message = "message=" + encodeURIComponent(JSON.stringify(
{
"text": "​Hi guys :)"
}
));
//loop throught user IDs (PSIDs)
for (var i=0; i<users; i++) {
var recipient = "recipient=" + encodeURIComponent(JSON.stringify({"id": users[i].id}));
var batchMessage = {
"method": "POST",
"relative_url":"v2.6/me/messages",
"body": recipient + "&" + message
};
multipleMessages.push(batchMessage);
}
form.append("access_token", token)
form.append("batch", JSON.stringify(multipleMessages));
res.send('Hi :)')
})
Try to move res.send('Hi') inside your request callback:
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Ok", response.statusCode);
res.send('Hi');
} else {
console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
}
});

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

Async request module in Node.js

I am creating a project using Node.js. I want to call my requests in parallel. For achieving this, I have installed the async module. Here is my code:
var requests = [{
url:url,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + req.cookies.apitoken
},
json: finalArr,
}];
async.map(requests, function(obj, callback) {
// Iterator function
request(obj, function(error, response, body) {
if (!error && response.statusCode == 200) {
// Transform data here or pass it on
var body = JSON.parse(body);
callback(null, body);
}
else {
var body = JSON.stringify(body);
console.log(body)
callback(error || response.statusCode);
}
});
})
I got undefined every time in console.log(body). When I am using GET requests using this module for other requests then everything works fine.
It looks like you're using the request module, but didn't tag it as such.
If I'm right, then your options object is incorrect, from the documentation there's not a data key that's respected. Instead, you should use body or formData or json depending on what kind of data you're pushing up. From your headers, I'd go with json.
var requests = [{
url:url,
method: 'POST',
headers: { // Content-Type header automatically set if json is true
'Authorization': 'Bearer ' + req.cookies.apitoken
},
json: finalArr,
}];

Trying to post api request

I having problem with making a API call to an external site.
I need to send a POST request to http://api.turfgame.com/v4/users with headers Content-type: application/js. But when I run this code it only loads and nothing more.
var request = require('request');
var options = {
uri: 'http://api.turfgame.com/v4/users',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
"name": "username"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
res.send(response.body);
}
});
The body need to be posted in json formate [{'name': 'username'}].
Can someone tell me what I have done wrong?
There are a few things wrong:
the address property in the "options" object should be "url" not
"uri"
you can use the "json" property instead of body
"res" is undefined in your response handler function
if you want the body to be an array, it needs to be surrounded in square brackets
here's a working sample that just logs the response:
var request = require('request');
var options = {
url: 'http://api.turfgame.com/v4/users',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
json: [{
"name": "username"
}]
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(response.body);
}
});

Resources