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
}
Related
I´m trying to create a function that make a request to a website and, as the return of the function, I want to deliver the object "BODY" created by the request. But everytime I have "Object undefined" return.
What I need to change in order to deliver this result ?
Here are the code:
// ---- Funções --------------------------------------------------------------------------------//
function consultaCep(cep){
request(`https://viacep.com.br/ws/${cep}/json/`, {json: true}, (err, res2, body) => {
if(err) return console.log(`Erro na consulta: ${err}`)
return body;
});
}
// Rotas ------------------------------------------------------------------------------------//
app.get('/', (req,res)=> {
x = consultaCep('13085485');
console.log(x);
res.end(x);
Thanks a lot.
There are many ways to achieve this. You can use a callback.
You can pass a callback to the method that invokes the web request, and invoke that callback from within that method:
var consultaCep = function(callback){
request('https://viacep.com.br/ws/${cep}/json/', function (error, response, body) {
if (!error && response.statusCode == 200) {
status = "succeeded";
callback(null, {status : status});
} else {
callback(error);
}
})
}
app.get('/', function(req, res){
consultaCep(function(err, result){
if(err){
res.send(500, { error: 'Something went wrong' });
} else {
res.send(result);
}
});
});
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);
});
When I'm trying to use create script(button try in custom DB connection or try connection) Auth0 use get user script. Examples:
enter image description here
And then Auth0 use get user script.
Here is my create script:
function create(user, callback) {
var request = require('request');
var API_ENDPOINT = configuration.ENDPOINT_LOCAL + "/api/create/account/";
user.user_metadata = user.user_metadata || {};
request.post({
url: API_ENDPOINT,
json: {
email: user.email,
password: user.password,
nickname: user.user_metadata.nickname,
employee_id: user.user_metadata.employee_id,
company_code: user.user_metadata.company_code,
email_verified: false
}
}, function (err, response, body) {
if (err) {
return callback(err);
}
if (response.statusCode != 200 && response.statusCode != 201) {
return callback(new Error('Forbidden'));
}
callback(null);
});
}
and Here is my get user script:
function getByEmail(email, callback) {
var request = require('request');
var IDP_ENDPOINT = configuration.ENDPOINT_LOCAL + "/api/account";
request.get({
url: IDP_ENDPOINT + '?email=' + email
}, function (err, response, body) {
if (err) {
return callback(err);
}
if (response.statusCode != 200) {
return callback(new Error('Forbidden'));
}
callback(null, JSON.parse(body));
});
}
I really don't know why because two days before all were working.
I'm running into a scenario where my meteor server call is posting to a remote URL and then returning the result. However, my meteor client is expecting a result right away and its receiving an empty string (the default return).
What is the correct way of implementing this?
Meteor.methods({
run: function(options){
return HTTP.post(apiUrl, {
params:
{
"headers": headers
}
},
function (error, result)
{
if (error)
{
console.log("error: " + error);
}
else
{
console.log("result: " + JSON.stringify(result));
console.log(result.content);
}
})
});
on my client
Meteor.call('run', '1', function(err,response) {
if(err) {
console.log(err);
return;
}else{
r = response;
console.log(JSON.stringify(r));
FileSystem.update({ _id: fileid }, { $set: {taskid:taskid} }, function (e, t) {
if (e) {
}else{
}
});
}
});
I'm expecting on the client side that it waits for the full result to come in which contains the desired data to save to data base (taskid).
You are calling HTTP.post asynchronously. Just remove the callback function and it becomes synchronous, i.e., you will get a return value that contains the result of the call:
Meteor.methods({
run: function(options){
return HTTP.post(apiUrl, {
params:
{
"headers": headers
}
});
});
});
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?