gpt4 book ai didi

node.js - Express.js 在路由之间传递 API 数据时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 03:14:24 27 4
gpt4 key购买 nike

我不知道如何在路由之间传递数据。我已经从 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;

Controller 文件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);
});
}

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

最佳答案

  1. 您在 Express 服务器的控制台中得到了什么?您收到回复了吗?您在 getSearchedFlights 函数中打印的那个。
  2. 如果您获得有效的控制台日志输出,那么您需要做的是确保您的响应到达 View 层(您的 .hbs 模板)。
  3. 因此,当您调用 .render 时,您必须通过参数将 Response 从 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 });

希望这有帮助。

关于node.js - Express.js 在路由之间传递 API 数据时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58873078/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com