Shehzad Lokhandwalla Shehzad Lokhandwalla - 1 year ago 65
JSON Question

How to pass information to the view after function completion when using NodeJS Request?

I'm writing code that would fetch some JSON data and pass it on to a new view with the given data.
The view is called /newbook2 and I want to pass information such as book name, author name and so on to the view from a JSON file called through an API.

var s_book_name;
var s_author_name;
var s_isbn13_id;
var s_publisher_name;
var s_category_id;
var error="";'/searchbook', function(req, res){

var isbn=req.body.isbn;
var url=""+isbn;
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
else error="Book not found. Please enter the information manually."


However, the information insn't yet loaded in my view. It seems like a common problem with asynchronous calls. However, I'm new to nodejs and would appreciate any help on how to fix it.

router.get('/newbook2', function(req, res){
res.render('newbook2', {title: 'Add New Book',s_book: s_book_name, s_author: s_author_name, s_isbn13: s_isbn13_id ,s_publisher: s_publisher_name , s_category: s_category_id});

Answer Source

You need to use promises for this. Here is some sample code for you to refer to make the POST call.'/newBook', function(req, res, next) {
    console.log('Please add your here to get the data from server');
    Obj.then(function() {
        res.send('You got the success response from the server');

res.send('Your Book has been successfully added.'); will only execute after you get the success response from the server. Please go through the concept of promises for more detail.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download