Passing array or nested objects in body of request npm - node.js

I have to send some parameters of String type along with one array in my body.
But it throws me an error message:
First argument must be String or buffer
Here is my code:
var tokenList = JSON.parse(req.body.tokenList);
var mobParams = {
"tokens": tokenList,
"profile": "<myprofile>",
"notification": {
"title": req.body.title,
"message": req.body.text
}
};
request({
method: "POST",
url: 'https://api.ionic.io/push/notifications',
headers: {
"content-type": "application/json",
"authorization": "Bearer ********"
},
body: (mobParams)
}, function(error, response, body){
console.log('Ionic push error', error);
console.log('IOnic push res', response);
console.log('IOnic push body', body);
if(!error){
return res.send({
code: 1,
message: "success"
});
}else{
return res.send({
code: 0,
message: error
});
}
How can I pass my array inside this object to request npm?
Also, I would like to add that this implementation works pretty fine through front-end but I have separate codebase which requires me to hit multiple FCM requests i.e. in a loop. So I would be happy to have a solution as neither ionic push nor FCM push works
For the FCM push I am trying the code below :
let desktopParams = {
"notification": {
"title": 'Merchant Portal Notifications',
"body": req.body.text
// "click_action" : action
},
"to": '/topics/' + topic
};
request({
method: "POST",
json: true,
url: 'https://fcm.googleapis.com/fcm/send',
headers: {
"content-type": "application/json",
"authorization": "key=****"
},
body: desktopParams
}, function(error, response, body){
console.log('error', error);
console.log('response', response);
console.log('body', body);
//return body;
});

you should try stringifying your tokenList & req.body.text before you join it with with the string (try to log it and post the outcome so that people will have a better idea about the objects...):
var cho = [{name:'john',lname:'cena'},{name:'mary',lname:'jane'}];
var che = {list:[{name:'john',lname:'cena'},{name:'mary',lname:'jane'}],group:'people'}
var mobParams = {
"tokens":JSON.parse(JSON.stringify(cho)),
"profile": "<myprofile>",
"notification": {
"title": "Some title",
"message":JSON.parse(JSON.stringify(che))
}
};
console.log(JSON.stringify(mobParams));//----->{"tokens":[{"name":"john","lname":"cena"},{"name":"mary","lname":"jane"}],"profile":"<myprofile>","notification":{"title":"Some title","message":{"list":[{"name":"john","lname":"cena"},{"name":"mary","lname":"jane"}],"group":"people"}}}
var arr = [{name:'john',lname:'cena'},{name:'mary',lname:'jane'}]
var js = JSON.stringify(arr);
var blabla = {'item':'something',js}
console.log(blabla); //-----> Object {item: "something", js: "[{"name":"john","lname":"cena"},{"name":"mary","lname":"jane"}]"}
var js = JSON.parse(JSON.stringify(arr));
var blabla = {'item':'something',js}
console.log(blabla); //-----> Object {item: "something", js: Array(2)}
var js = JSON.parse(arr);
var blabla = {'item':'something',js}
console.log(blabla); //-----> "SyntaxError: Unexpected identifier"

Related

Error 400 on trying to add a contact in mailchimp

I am getting this error when trying to call the mailchimp API V3 to add a new contact to my list
"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"Invalid Resource","status":400,"detail":"The resource submitted could not be validated. For field-specific details, see the \'errors\' array.","instance":"f8b79d9b-1c02-4062-a0e4-847e31f7bd61","errors":[{"field":"","message":"Schema describes object, NULL found instead"}]}'
Here is the code used:
app.post("/", function(req,res){
var email = req.body.email;
var data = {
members : [
{
email_address: email,
status: "subscribed"
}
]
};
var jsonData = JSON.stringify(data);
var options = {
headers :{
'Authorization': 'thomas APIKEY',
'Content-Type': 'application/json',
'Content-Length': jsonData.length
},
url: "https://us20.api.mailchimp.com/3.0/lists",
method: "POST",
data:jsonData
};
console.log(options);
request(options, function(error, response, body){
if(error)
{
console.log(error);
}
else{
console.log(response);
}
})
I tried adding /Listkey/members to my url with no success
Do you have some tips? Thank you
I found the solution, the elements passed to request were not good.
Here is the functional code:
app.post("/", function(req,res){
var email = req.body.email;
var data = {
"email_address": email,
"status" : "subscribed"
};
var options = {
"url": "https://us20.api.mailchimp.com/3.0/lists/c9b9a6e109/members/",
"method": "POST",
"headers": {
"Authorization": "thomas APIKEY"
},
"body": data,
"json": true
};
})

Show json url to messenger bot

I want to show data from JSON URL on my facebook messenger bot. I've tried with a lot of code approach. However, I couldn't still get it. I just could show the data the terminal with console.log.
This is the code I use to get data from JSON URL:
const ambilDataProfil = (sender_psid) => {
//sorry this url below is not valid I write intentionally for my privacy data.
request({
url: 'https://sorry-url-privately.firebaseio.com/server/saving-data/users.json',
method: "GET",
}, function(error, response, body){
let jsonBody = JSON.parse(response.body);
let resp = jsonBody.Ndus;
console.log(resp);
let respon = {"text": "resp"};
callSendAPI(sender_psid, respon);
}
// console.log(body.Ndus.goldar);
);
};
function callSendAPI(sender_psid, response) {
// Construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"message": response
}
// Send the HTTP request to the Messenger Platform
request({
"uri": "https://graph.facebook.com/v2.6/me/messages",
"qs": { "access_token": PAGE_ACCESS_TOKEN },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
console.log('message sent!')
} else {
console.error("Unable to send message:" + err);
}
});
}

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

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

How to add a file attachment via NodeJS REST request

There's some documentation on the Jira site on how to add an attachment to an issue via a curl request here: https://confluence.atlassian.com/display/JIRAKB/How+to+attach+an+attachment+in+a+JIRA+issue+using+REST+API
This is the code that I used to successfully create an issue:
var request = require("request");
var auth = "Basic " + new Buffer("user:password").toString("base64");
var options = {
uri: 'http://domain.com/rest/api/2/issue/',
headers : {
"Authorization" : auth
},
method: 'POST',
json: {
"fields": {
"project": {
"id": "10000"
},
"summary": summary,
"description": description,
"issuetype": {
"name": "Bug"
},
"customfield_10003": {"value": value}
}
}
};
request(options, function (error, response, body) {
if (!error) {
console.log("Success");
}
});
So in order to add an attachment to a ticket with the ID of 1200, I would think I would do something like this:
var options = {
uri: 'http://domain.com/rest/api/2/issue/1200/attachment/',
headers : {
"Authorization" : auth,
"X-Atlassian-Token" : nocheck
},
method: 'POST',
json: {
"fields": {
"file" : "filename.txt"
}
}
};
But have had no luck.
Edit: Getting somewhere. Here's what I've got:
var request = require('request');
var fs = require("fs");
var auth = "Basic " + new Buffer("user:password").toString("base64");
var formData = {
file: {
value: fs.createReadStream('file.txt'),
options: {
filename: 'file.txt',
contentType: 'text/plain'
}
}
};
request.post({
url:'http://domain.com/rest/api/2/issue/14000/attachments/',
headers : {
"Authorization" : auth,
"X-Atlassian-Token" : "nocheck"
},
formData: formData
}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
And it uploads a file called file.txt but when I look at the attachment it prints out a stack trace that starts out like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><status><status-code>500</status-code><stack-trace>java.lang.NullPointerException
at com.atlassian.plugins.rest.common.security.jersey.XsrfResourceFilter.mediaTypeToString(XsrfResourceFilter.java:91)
at com.atlassian.plugins.rest.common.security.jersey.XsrfResourceFilter.isXsrfable(XsrfResourceFilter.java:76)
at com.atlassian.plugins.rest.common.security.jersey.XsrfResourceFilter.filter(XsrfResourceFilter.java:54)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:277)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
You first try:
var options = {
uri: 'http://domain.com/rest/api/2/issue/1200/attachment/',
headers : {
"Authorization" : auth,
"X-Atlassian-Token" : nocheck
},
method: 'POST',
json: {
"fields": {
"file" : "filename.txt"
}
}
};
will not work because as it's not supported. Check Jira attachment documentation
So, probably you need to restructure your formData object to be
var formData = {
file: fs.createReadStream('file.txt'),
};
No need for editing meta data if you don't need them. Also make sure you've got a valid stream of your file.
About stacktrace, I see stack frames related to XSRF despite adding "X-Atlassian-Token" header which doesn't make any sense for me.

Resources