0

我不知道如何在路由之间传递数据。我已经从 API 成功获取了 json 数据,但现在我想将该数据传递给 index.hbs 但我不知道如何。我已将所有代码放在下面。

主文件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 文件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;

控制器文件控制器/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);
  });
}

++模板引擎文件**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>
4

1 回答 1

3
  1. 您在快递服务器的控制台中得到了什么?你得到回应了吗。您在 getSearchedFlights 函数中打印的那个。
  2. 如果您获得有效的控制台日志输出,那么您需要做的是确保您的响应到达视图层(您的 .hbs 模板)。
  3. 因此,当您调用 .render 时,您必须通过参数将来自 skyscanner api 的响应传递给您的 hbs 模板,您可以使用它作为参考
    https://medium.com/programming-sage/handlebars-in-node-js-tutorial- a30a41fc6206 它会告诉你如何在上面做。

现在,您没有对获得的响应做任何事情。还有这两行 res.redirect('/'); 的顺序 获取数据(数据);

应该反过来

您应该从 getData 函数返回数据并将其传递给您的模板。

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

希望这可以帮助。

于 2019-11-15T08:58:38.400 回答