Shehzad Lokhandwalla Shehzad Lokhandwalla - 5 months ago 12
Javascript Question

How to pass information to view from controller in NODE JS Express

I'm quite new to NodeJS. I'm trying to create a form that accepts several inputs. One of the functions of the form is to take in an input--> ISBN and automatically get information from an API and add it in the input fields. However, I cannot pass information from the controller to the view.

I have a view:

newbook.jade

Which has two forms

form#form_search_book(name="search", method="post", action="/searchbook")
span ISBN
span  
input#input_isbn(type="text", placeholder="isbn", name="isbn")
button#search_book(type="search") search
br
br
form#form_add_book(name="addbook", method="post", action="/addbook")
span Book Name
span  
input#input_name(type="text", placeholder="book name", name="book_name")


And I have the NodeJS controller:
index.js
that executes the /searchbook form and then redirects back the /newbook page. When it redirects to the new book page, the information from the API should be passed on to the input form...but I've been struggling on how to do that.
Any help would be appreciated.

router.get('/newbook', function(req, res){
res.render('newbook', {title: 'Add New Book' });

router.post('/searchbook', function(req, res){
var isbn=req.body.isbn;
var url="http://isbndb.com/api/v2/json/63JEP95R/book/"+isbn;
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body.data\[0\].isbn13) // Print the json response
}
});
res.redirect('/newbook');
document.getElementById('input_name').value=body.data\[0\].title;
document.getElementById('input_isbn').value=body.data\[0\].isbn13;


});
});


Link to the view

Answer

I think you got confused about what code's being run in the client-side and what code run in server-side. This code works only on a browser not in NodeJS.

document.getElementById('input_name').value='......';

you need to pass your values through a querystring in redirect method.

I presume you can find your answer in this post : How do I redirect in expressjs while passing some context?

Comments