将数据从请求转移到车把模板?

时间:2019-05-13 14:00:36

标签: javascript node.js express express-handlebars

我有几个请求,包括天气(openweathermap.org),推文(twitter.com)和照片(unsplash.com)。这些请求起作用,将数据接收到控制台。我使用Express-Handlebars显示模板。我不知道如何将数据从请求传递到模板。传递了诸如String,Int之类的单个值,但是来自包含请求的函数的信息不会传输到模板。我试图以各种方式从请求中发送数据,但没有任何帮助。我该怎么做才能从请求中获取数据并将数据发送到HandleBars模板?

路由很好,一切都按需进行,主要问题是将数据从请求传输到HandleBars模板。

unsplash.js

var request = require('request');

module.exports = {
    unsplash: function (town){
        request({url:'https://api.unsplash.com/search/photos?page=1&query=' + town +'&client_id=ab132a1b9b1c45a089418f5ae851b088260a08967b068620f340f6bf763ea196'}, function(err, res){
            if(err){
                console.log("Something with unsplash is wrong! Error: " + err.message);
            }else if(res){
                var search = JSON.parse(res.body);
                var array = new Array();
                search.results.forEach((e) => {
                    array.push(e.urls.raw);
                });
                console.log(array);
                return array;
            }
        })
    }
};

mainController.js

const express = require('express');
var router = express.Router();
var common1 = require('./unsplash');

router.get('/tokyo', (req, res) => { 
    res.render("hotel/mainPage", {
        viewTitle: "> TOKYO",
        array: common1.unsplash("tokyo")
    });
});

module.exports = router;

hotel / mainPage.hbs

...
<body>
 {{viewTitle}} <-- it works
 {{array}} <-- did not work
 {{log array}} <-- In the console I get 'undefined'
</body>
...

server.js

const express = require('express');
const path = require('path');
const exphbs = require('express-handlebars');
const bodyparser = require('body-parser');
const Handlebars = require('handlebars');

var app = express();
app.use(bodyparser.urlencoded({
    extended: true
}));
app.use(bodyparser.json());

app.set('views', path.join(__dirname, '/views/'));

var common = require('./controllers/unsplash');

app.engine('hbs', exphbs({ extname: 'hbs', defaultLayout: 'mainLayout', layoutsDir: __dirname + '/views/layouts/'}));

app.set('view engine', 'hbs');

app.listen(3000, () => {
    console.log('Express server started at port : 3000');
});

我希望URL照片像在控制台中一样: ['https://images.unsplash.com/photo-1503899036084-c55cdd92da26?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjcwNTc0fQ',   'https://images.unsplash.com/photo-1502716197620-bf14ce1651b3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjcwNTc0fQ']

但是实际输出没有。

如果通过这种方式键入它: {{log array}} 在控制台中,我得到: 未定义

0 个答案:

没有答案