0

I don't know how to pass data between routes. I have fetched json data successfully from an API but now I want to pass that data to index.hbs but iIdon't know how. I have put all code below.

Main file app.js

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

indexRouter file routes/index.js

var express = require('express');
var router = express.Router();

const index = require('../controllers/index');

router.get('/', index.index);
router.post('/', index.recieve_post);


module.exports = router;

controllers file controllers/index.js

const request = require('request');
let objData = {};

exports.index = function (req, res, next) {
  res.render('index', {
    title: 'Express'
  });
}

exports.recieve_post = function(req, res, next) {
  const data = req.body;
  res.redirect('/');
  getData(data);
}

function getData(data){
  const options = {
     method: 'POST',
     url: 'https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/pricing/v1.0',
     headers: {
       'x-rapidapi-host': 'skyscanner-skyscanner-flight-search-v1.p.rapidapi.com',
       'x-rapidapi-key': 'API_KEY',
       'content-type': 'application/x-www-form-urlencoded'
     },
     form: {
       inboundDate: data.inboundDate,
       cabinClass: data.cabinClass,
       children: '0',
       infants: '0',
       country: 'US',
       currency: 'USD',
       locale: 'en-US',
       originPlace: data.originPlace,
       destinationPlace: data.destinationPlace,
       outboundDate: data.outboundDate,
       adults: '1'
     }
   };
   request(options, function (error, response, body) {
    if (error) throw new Error(error);
     const session_key = response.headers.location.split('/')[7];
     getSearchedFlights(session_key);
   });
}

function getSearchedFlights(key){
  const options = {
    method: 'GET',
    url: 'https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/pricing/uk2/v1.0/'+key,
    qs: {pageIndex: '0', pageSize: '10'},
    headers: {
      'x-rapidapi-host': 'skyscanner-skyscanner-flight-search-v1.p.rapidapi.com',
      'x-rapidapi-key': 'API_KEY'
    }
  };
  request(options, function (error, response, body) {
    if (error) throw new Error(error);
    objData = JSON.parse(body);
    console.log(objData);
  });
}

++Template Engine file** views/index.hbs

<h1>{{title}}</h1>

<form class="form" action="/" method="POST">
    <input type="text" name="inboundDate" placeholder="inboundDate">
    <input type="text" name="cabinClass" placeholder="cabinClass">
    <input type="text" name="originPlace" placeholder="originPlace">
    <input type="text" name="destinationPlace" placeholder="destinationPlace">
    <input type="text" name="outboundDate" placeholder="outboundDate">
    <input type="submit" name="submit" value="search">
</form>

<!-- I want to get json data here -->
<p>{{objData}}</p>
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Salman Hilabi
  • 11
  • 1
  • 1

1 Answers1

3
  1. What are you getting in the console of your express server? Are you getting the response. The one you have printed in your getSearchedFlights function.
  2. If you are getting a valid console log output then what you need to do is to ensure your response reaches the view layer(Your .hbs template).
  3. so you would have to pass the Response from skyscanner api to your hbs template via parameters when you call .render you can use this for reference
    https://medium.com/programming-sage/handlebars-in-node-js-tutorial-a30a41fc6206 it'll show you how to do above.

Right now you aren't doing anything with your obtained response. Also the order of these two lines res.redirect('/'); getData(data);

should be the other way around

You should return your data from getData function and pass it onto your template.

 var obtainedInformation = getData(data);
 res.render('templateName',{ data:obtainedInformation });

Hope this helps.

amatrue
  • 61
  • 5
  • amatrue, thanks for the reply brother, Yes i got the json data in the getSearchedFlights function after passing the key in getData function and now i want to pass objData to the template view – Salman Hilabi Nov 15 '19 at 09:07
  • @SalmanHilabi you'll need to pass data via render method, the medium article would let you know how. instead of redirecting the user (res.redirect) use render a template using the data. – amatrue Nov 15 '19 at 12:13