Callback function not working in POST request - javascript

İ'm using Node.js , ExpressJS(5.0.0-alpha.1) and request module
This is POST request
app.post('/generateTags', function(req, res) {
var title = req.body.title;
restApiKeywords(title, function(tags) {
console.log(tags);
});
});
});
My callback function;
function restApiKeywords(postTitle,callback){
request_('blabla'+postTitle,{json:true,encoding: "binary"}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var data = body[1];
if (typeof(callback) === 'function') {callback(data);}
}
});
}
if i call this function in GET method, it is working;
app.get("/test",function(req, res) {
restApiKeywords("Recep Niyaz", function(tags) {
console.log(tags);
});
});
How can i run this fuction into POST request basically ?
FİXED:it is my stupid issue , i created two same post method on same project , sorry my friends :)

Related

How to pass res from one function to another?

FB.api('4', function (res) {
if(!res || res.error) {
console.log(!res ? 'error occurred' : res.error);
return;
}
console.log(res.id);
console.log(res.name);
});
// viewed at http://localhost:8080
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
Ive created this small FB.api call which return some data. Now I want to display this data when accessing localhost:8080/test, how do I do that? what is the way to do stuff like that? Can someone point me to some documentation of possible?
First you add your FB.api call inside an express route like this
app.get('/something', function(req, res) {
FB.api('4', function (result) {
if(!res || res.error) {
return res.send(500, 'error');
}
res.send(result);
});
});
Then inside index.html you can add some javascript to your page and create an XHR to call 'localhost:8080/something' like that
index.html
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8080/something');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var data = xhr.responseText;
//Do whatever you want with this data.
}
}
xhr.send();
</script>

Node.js and Express: Updating router.get and res.render's object after load

I have this code, which is returns the following error on req.body.firstname.length inside router.use on the page load:
TypeError: Cannot read property 'length' of undefined
Because already checking the input forms value and the default value is undefined. I want to only check this code when it's getting req.xhr request from the AJAX form, not on the page load. Is there a way to achieve this?
router.use((req, res, next) => {
if(req.body.firstname.length === 0) {
var validateFirstname = false;
} else {
var validateFirstname = true;
};
if(validateFirstname === true && validateCaptcha === true) {
console.log('SUCCESS: Form validated!');
} else {
console.log('ERROR: Form not validated!');
};
next();
});
The reason why it's in a router.use, not in router.post, because I want to share this logic for router.get also, where my template rendering resides.
UPDATE:
Here is the relevant full code to get the idea what's going on:
/////////////////////////////////////////////////////////////
// Nodemailer MIDDLEWARE
/////////////////////////////////////////////////////////////
router.post('/', (req, res, next) => {
const firstname = req.body.firstname;
req.firstname = firstname;
if(req.firstname.length === 0) {
var validateFirstname = false;
} else {
var validateFirstname = true;
};
if(validateFirstname === true) {
console.log('SUCCESS: Form validated!');
// send mail with defined transport object
req.sending = true;
} else {
console.log('ERROR: Form not validated!');
req.sending = false;
};
next();
});
router.use((req, res, next) => {
// create reusable transporter object using the default SMTP transport
req.transporter = nodemailer.createTransport({
...
});
// setup e-mail data with unicode symbols
req.mailOptions = {
...
};
next();
});
/////////////////////////////////////////////////////////////
// Nodemailer
/////////////////////////////////////////////////////////////
router.post('/', (req, res, next) => {
if(!req.xhr && req.sending === true) {
// send mail with defined transport object
req.transporter.sendMail(req.mailOptions, (err, info) => {
if(err) {
console.log('Error occurred');
console.log(err.message);
}
console.log('Message sent successfully!');
console.log('Server responded with "%s"', info.response);
res.send('<div class="form-validation-success">SUCCESS: Message sent successfully!</div>');
});
} else {
res.send('<div class="form-validation-error">ERROR: Message cannot be sent!</div>');
};
/////////////////////////////////////////////////////////////
// INTERNAL API
// GET Contact page
/////////////////////////////////////////////////////////////
router.get('/', (req, res, next) => {
res.render('contact', {
title: 'Contact',
formValidationError: req.displayBlock
});
});
In my handebars template:
<div id="responseText"></div>
This code is now working but not updating the already rendered viewing template. I guess to only way to solve this to handle the server's response with AJAX, but how? This is the client-side AJAX code:
'use strict';
(function() {
document.getElementById('xhr').onclick = function() { makeRequest(); };
function makeRequest() {
var firstname = document.getElementById('firstname').value;
var data = { firstname: firstname };
// instance of a class that provides this functionality
var xhr = new XMLHttpRequest();
// decide what you want to do after you receive the server response to your request
xhr.onreadystatechange = function() {
try {
// process the server response
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// everything is good, the response is received
//alert(xhr.responseText);
document.getElementById('responseText').innerHTML = xhr.responseText;
} else {
// still not ready
alert('There was a problem with the request.');
};
} catch(e) {
console.log('Caught Exception: ' + e.description);
};
};
// make the request
xhr.open('POST', '/en/contact', true);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.send(JSON.stringify(data));
};
})();
It's always returning the There was a problem with the request error message, even when also returning xhr.responseText.
This router file resides at routes/contact.js and handling the requests at /:lang/contact. That's why you see '/' url in the file.
can you please add some more information on it....as it is very difficult to figure out the problem with this information.
you are trying a post on uri /en/contact
but receiving a request on /

Getting undefined for function call in Express render() [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I'm new to Node and Express, and am running into trouble getting data from one function, to pass into another function as a var. I presume that this is because I am not handling the callback and async stuff properly, but would appreciate a steer.
The code should hopefully be explanatory. I am attempting to retrieve some JSON data from a URL, and pass it to the router.get function's render() method. However, nothing ("undefined") gets sent instead. When I run the getData() function separately, however, it returns the correct data, so as stated, I presume this is because I'm not handling the async stuff correctly.
function getData(cid){
var request = require("request");
var cid ='XXXXXX' // hard code temp
var baseUrl = "someurl.com"
var apiKey = "XXXXXX"
var cUrl = baseUrl+cid+'?api_key='+apiKey
request({
url: cUrl,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body._embedded.assets); //Print the json response
return body._embedded.assets
}
});
}
/* GET home page. */
router.get('/', function(req, res) {
var LiveCards = getData()
var cID = (req.query.cID
? req.query.cID
: '14d115ff-1db7-4a6f-8648-ea64bc1a6597')
var limit = Number(req.query.limit)
res.render('index', {
title: 'Cards',
cards: LiveCards.slice(0,limit), <--- returning undefined at the moment
limit: limit,
activateSharetools: activateSharetools,
cID: cID,
cardsHeader: req.query.cardsHeader,
});
});
Any guidance appreciated.
request is asynchronous function, you need add callback to get Data and execute it after completes the request, like this:
function getData (cid, callback) {
var request = require("request");
var cid = 'XXXXXX';
var baseUrl = "someurl.com";
var apiKey = "XXXXXX";
var cUrl = baseUrl + cid + '?api_key=' + apiKey
request({url: cUrl, json: true}, callback);
}
router.get('/', function (req, res) {
var cID = req.query.cID ? req.query.cID : '14d115ff-1db7-4a6f-8648-ea64bc1a6597');
var limit = Number(req.query.limit);
getData(cID, function (error, response, body) {
if (!error && response.statusCode === 200) {
res.render('index', {
title: 'Cards',
cards: body._embedded.assets.slice(0, limit), <--- returning undefined at the moment
limit: limit,
activateSharetools: activateSharetools,
cID: cID,
cardsHeader: req.query.cardsHeader,
});
} else {
throw error;
}
});
});

Creating a simple oEmbed system in Nodejs

For a personal project I'm trying to create a simple oEmbed system using Nodejs.
My route looks like this:
app.get('/oembed/:url', function (req, res) {
oembed.get(req.params.url, function (error, result) {
return res.json(200, {message: "OK"});
});
});
and oembed is exposed using var oembed = require('../oembed');
For the oembed.js itself I have:
var request = require('request');
exports.get = function(url, callback) {
//this bit will be developed to call different functions depending on the URL
html = vimeo(url)
};
function vimeo(url) {
var videoUrl = url;
var endpoint = 'http://www.vimeo.com/api/oembed.json';
var url = endpoint + '?url=' + encodeURIComponent(videoUrl) + '&width=640';
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
var video = JSON.parse(body);
return video.html
}
})
}
So far, the vimeo function returns the desired html to the function call but I'm a bit lost from here. I'm not sure how I return the html to the initial request (the oembed.get part) and utilise the callback's error and result parameters.
Any help (and advice) would be much appreciated.
It seems you just don't understand how callback functions work. You need something like this in your oembed.js file:
var request = require('request');
exports.get = function(url, callback) {
var endpoint = 'http://www.vimeo.com/api/oembed.json';
request(endpoint + '?url=' + encodeURIComponent(url) + '&width=640', function (error, response, body) {
if (!error && response.statusCode == 200) {
try {
callback(null, JSON.parse(body).html);
} catch (error) {
callback(error);
}
}
});
};
And your route should look like this:
app.get('/oembed/:url', function (req, res) {
oembed.get(req.params.url, function (error, result) {
if (error) {
res.json(500, {message: error});
} else {
res.json(200, {message: "OK"});
}
});
});

Redis connection close

Im using connect-domain and connect-redis. Below code checks for redis cache in Redis database.
function redis_get(key, req, res) {
var redisClient = redis.createClient();
redisClient.get(redisKey, function (err, data) {
if (err) {
console.log("Error in RedisDB");
}
else if (data == null) {
// Calling external function
}
else {
// Calling external function
}
redisClient.quit(); // Not working
});
}
When cache is not avaiable Im calling external function. I want redis connection to be closed once the cache check has been done.
redisClient.quit() // Not working
Any help on this will be really helpful.
Thanks
Below code is working fine without any problem.So check your status reply in the quit method if you get status as 'OK' means that method is working fine.
var redis=require('redis');
var redisClient = redis.createClient();
redisClient.get('name', function (err, data) {
if (err) {
console.log("Error in RedisDB");
}
else if (data == null) {
console.log('null');
}
else {
console.log(data);
}
redisClient.quit(redis.print);
});

Categories