JavaScript needle.put object not being parsed - javascript

Folks, trying to put the following object using the needle.js library:
var object = {
fName: 'Jasmine',
lName: 'Tests'
}
var options = {
json: true,
accept: 'application/json'
}
needle.put(url, object, options, function (err, resp, body) {
if (err) {
console.log ('post error',err);
callback (err, null);
} else {
console.log ("RETURNED", body)
callback (null, resp, body);
}
})
I get back:
RETURNED { code: 'InternalError', message: 'Unexpected token o' }
The Express API tries to do a JSON.parse() on an incoming request and fails. Any suggestions?
Thanks!

Related

Make dynamic/re-usable method

I need to use sendMessage in other method.
Like:
SendMessage('abc#expample.com','abc#exapmle.com','subject','body').
I am new to nodejs. Just need some syntax help.
I have tried
SendMessage.makeBody('','','','');
But its giving me error.
TypeError: sendMessage.makeBody is not a function
function sendMessage(auth) {
const raw = makeBody(
'abc#example.com',
'abc#example.com',
'something',
'something');
gmail.users.messages.send({
auth: auth,
userId: 'me',
resource: {
raw: raw
}
}, function(err, response) {
if (err) {
logger.info('The API returned an error: ' + err);
return;
}
logger.info(response);
});
}
module.exports = {
sendMessage
};
function sendMessage(data) {
gmail.users.messages.send({
auth: data.auth,
userId: 'me',
resource: {
raw: data.raw
}
}, function(err, response) {
if (err) {
logger.info('The API returned an error: ' + err);
return;
}
logger.info(response);
});
}
let raw = makeBody('abc#example.com','abc#example.com','something','something');
let data = {raw: raw, auth: auth}
// pass raw and auth both in a object and use it into sendMessage funtion.
sendMessage(data)
module.exports = {
sendMessage
};

Facebook creating ad-sets api not working when adding params as post body(v2.12)

I met similar issue several times.
Below is success call
var createAdset_params = {
method: "post"
}
var url = "https://graph.facebook.com/v2.12/act_"+req.body.ADACCOUNT_ID+"/adsets?access_token="+req.body.access_token +
"&name=My+Reach+Ad+Set"+
"&optimization_goal=REACH"+
"&billing_event=IMPRESSIONS"+
"&bid_amount=2"+
"&daily_budget=1000"+
"&campaign_id="+req.body.CAMPAIGN_ID+
"&targeting=%7B%22geo_locations%22%3A%7B%22countries%22%3A%5B%22US%22%5D%7D%7D"+
"&status=PAUSED"+
"&promoted_object%3A%20%7B"+
"page_id%3A%20%"+req.body.PAGE_ID+"%22%7D";
request({url:url, qs: createAdset_params}, function(err, response, body) {
if(err) {
console.log(err); return;
}
console.log("create adset result", body);
res.send(body);
});
Create ad set and return id of adset.
Below is not success call.
var createAdset_params = {
method: "post"
name:"My Reach Ad Set",
promoted_object: {page_id: req.body.PAGE_ID},
optimization_goal: "REACH",
billing_event:"IMPRESSIONS",
bid_amount:2,
daily_budget:1000,
campaign_id:req.body.CAMPAIGN_ID,
status: "PAUSED",
targeting:{
geo_locations: {countries:["US"]}
}
}
var url = "https://graph.facebook.com/v2.12/act_"+req.body.ADACCOUNT_ID+"/adsets?access_token="+req.body.access_token;
request({url:url, qs: createAdset_params}, function(err, response, body) {
if(err) {
console.log(err); return;
}
console.log("create adset result", body);
res.send(body);
});
Showing admin permission error, even if the access_token is admin's access_token which is success with on first call.
Is there someone success with the format of below one(regular post request format)?
Any kind of hint will greatly appreciate!
If you are checking facebook marketing api doc, to create an adset all parameters are posted as form, instead of query string.
var createAdset_params = {
name:"My Reach Ad Set",
promoted_object: {page_id: req.body.PAGE_ID},
optimization_goal: "REACH",
billing_event:"IMPRESSIONS",
bid_amount:2,
daily_budget:1000,
campaign_id:req.body.CAMPAIGN_ID,
status: "PAUSED",
targeting:{
geo_locations: {countries:["US"]}
},
access_token: req.body.access_token
};
var url = "https://graph.facebook.com/v2.12/act_"+req.body.ADACCOUNT_ID+"/adsets";
request({
url : url,
method: 'POST',
form: createAdset_params
}, function(err, response, body) {
if(err) {
console.log(err); return;
}
console.log("create adset result", body);
res.send(body);
});

Purging Cloudflare cache with an API call in Node.js

I'm looking to purge Cloudflare's cache through its API. More specially, the purge all files command.
However, I keep running into the "Invalid Content-Type header, valid values are application/json,multipart/form-data" error message, despite explicitly setting the Content-Type header with Node.js' request package.
What am I missing?
var request = require('request');
gulp.task('cfPurge', function() {
var options = {
url: 'https://api.cloudflare.com/client/v4/zones/myZoneID/purge_cache',
headers: {
'X-Auth-Email': 'email',
'X-Auth-Key': 'myAPIkey',
'Content-Type': 'application/json'
},
form: {
'purge_everything': true,
}
};
function callback(error, response, body) {
var resp = JSON.parse(body);
if (!error & response.statusCode == 200) {
console.log('CF Purge: ', resp.success);
}
else {
console.log('Error: ', resp.errors);
for (var i = 0; i < resp.errors.length; i++)
console.log(' ', resp.errors[i]);
console.log('Message: ', resp.messages);
console.log('Result: ', resp.result);
}
}
return request.post(options, callback);
});
Output:
Error: [ { code: 6003,
message: 'Invalid request headers',
error_chain: [ [Object] ] } ]
{ code: 6003,
message: 'Invalid request headers',
error_chain:
[ { code: 6105,
message: 'Invalid Content-Type header, valid values are application/json,multipart/form-data' } ] }
Message: []
Result: null
According to the documentation for the cloudfare API, you need to send an HTTP DELETE request and not an HTTP POST request:
Modify the line...
return request.post(options, callback);
...with:
return request.del(options, callback);
Also, this is not a form. You need to put the JSON in the body of the data. So, replace the block...
form: {
'purge_everything': true,
}
...with:
body: JSON.stringify({'purge_everything': true})

How to pass a callback data to second function in Node.js?

I'm using tcp-ping to ping a server, and then I want to make a callback function that will POST the data to my database via the request library. I'm having trouble figuring out how to get the callback to send data to the second function.
The problem is that there is no error, but the form data for Min, Max, and Avg are not being recorded in mongodb. I don't know how to retrieve the data, or know if the data is even being sent.
tcpp.ping({ address: 'www.google.com' }, function(err, data) {
postPingData(function(err, data){
if(err){
console.log(500, { error: 'something blew up' });
} else {
console.log(data); // I understand this is incorrect, but I don't know how else I'm supposed to send data.
}
});
console.log(data);
});
var postPingData = function(callback){
console.log(callback);
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:8080/api/pingdata',
form: {
ping_id: "5852fd1976ba7111cd9b78aa",
min: callback.min,
max: callback.max,
avg: callback.avg
}
}, function(error, response, body){
if (!error && response.statusCode == 200) {
status = "succeeded";
callback(null, {status : status});
} else {
callback(error);
}
})
};
Essentially it seems you would want to inject the data argument passed to the callback to tcpp.ping - which will be the result of the ping operation if successful - to your postPingData function:
tcpp.ping({ address: 'www.google.com' }, function(err, data) {
postPingData(data, function(err, data){
...
var postPingData = function(data, callback){
...
form: {
ping_id: "5852fd1976ba7111cd9b78aa",
min: data.min,
max: data.max,
avg: data.avg
}

Slack slash command: set bot name and icon

I'm trying to make a node slack bot. When I hit the route from Slack,
app.get('/testbot', testbot);
I call testbot:
testbot.js:
postToSlack(botPayload, function (error, status, body) {
console.log('successfully posted to slack');
});
I'm posting my payload object to the Webhook URL specified in their Slack API: "https://hooks.slack.com/services/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"
function postToSlack (payload, callback) {
var val = JSON.stringify(payload);
request({
uri: 'https://hooks.slack.com/services/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&payload=val',
method: 'POST'
}, function (error, response, body) {
if (error) {
return callback(error);
}
console.log('RESPONSE', body); //takes forever, then eventually comes back as { }
callback(null, response.statusCode, body);
});
}
console.log('RESPONSE', body) doesn't return anything.
My test botPayload object looks like:
var botPayload = {};
botPayload.text = 'This should be working';
botPayload.username = 'my_new_bot';
botPayload.channel = '#mychannel';
botPayload.icon_url = 'http://i.imgur.com/IciaiJt.png';
What am I doing wrong here?
How can I remove the BOT label from the post?

Categories

Resources