Shehzad Lokhandwalla
Shehzad Lokhandwalla

Reputation: 11

NodeJS Express pass values during redirect

I have a post function that get's some information from the view and stores processed values in variables declared in the scope of the function

   router.post('/searchbook', function(req, res, next){
    var s_book_name="n/a";
    var s_author_name="n/a";
    var s_isbn13_id="n/a";

    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 && body.data!=null && response.statusCode === 200) {
                if(body.data[0].title!=null)
                  s_book_name=body.data[0].title;
                if(body.data[0].author_data[0]!=null)
                  s_author_name=body.data[0].author_data[0].name;
                if(body.data[0].isbn13!=null)
                  s_isbn13_id=isbn;
              }
          else 
          { error="Book not found. Please enter the information manually.";
            res.redirect('/newbook');
          }
    }).then(function() {
        res.redirect('/newbook2');
      });
    });

Now I have a get function that should send this information to another view.

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});
    });

But the information in the view is always shown as undefined. I believe the values used in the get function is outside the scope. Should I use global variables? Is there another way of doing this.

Upvotes: 0

Views: 812

Answers (1)

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15290

Either you should use app#locals to set the variable available throughout app.

Or you can pass the data using query string parameter and access it using

Without expressJs

var url  = require('url');

http.createServer(function(req,res){
    var url_parts = url.parse(req.url, true);
    var query = url_parts.query;

    console.log(query); //
})

Using expressJS,you can use req#query

app.get('/path',function(req,resp){
      req.query // get querystring 
})

Upvotes: 2

Related Questions