无法以html格式呈现JSON-node.js

时间:2018-09-29 04:58:58

标签: javascript html json node.js express

这可能是一个简单的解决方案,但是我无法弄清楚如何将JSON对象传递到视图中。通常,您会将JSON放入app.get内部的res.render()中。不幸的是,我遇到了麻烦。出现问题是因为我需要能够将表​​单数据从html发送到我的API请求,然后获取该JSON对象并在我的视图中显示它。我可以在控制台中看到它,但是无法将其传递到html。希望获得有关如何改进我的代码或找到解决方案的帮助或指导。任何帮助表示赞赏! -查看下面的代码:

Server.js

var path = require('path');
var express = require('express');
var exphbs  = require('express-handlebars');
var bodyParser = require('body-parser');
var Bls2 = require('bls2');

var app = express();

app.engine('html', exphbs({ extname: '.html' }));
app.set('view engine', 'html');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

var blsRequest = function(req, res, inputContent){
    const API_KEY = //bls API key here
    let bls = new Bls2(API_KEY);
    console.log('this is seriesID =', inputContent);

    let options = {
        'seriesid': [inputContent],
        'startyear': '2008',  
        'endyear': '2018',
        // ...
    };

    bls.fetch(options).then(function (response) {
        var data = JSON.stringify(response)
        console.log(data);
        console.log('API Call Complete')

        res.send({data : data}); //need to render home view and JSON HERE
    });
}

app.get('/', function (req, res) {

    res.render('home');
});

app.post('/', function(req, res){
    let inputContent = req.body.seriesID;
    blsRequest(req, res, inputContent);

});

app.listen(8000);

html

<!DOCTYPE html>
<html>
<head>
    <title>LBS</title>
    <meta charset="utf-8">
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="crossorigin="anonymous"></script>
</head>
<body>
    <div class="container-fluid">
        <form id="seriesID">
            <div class="form-group" method="post" action='/'>
                <label for="seriesID">Input Series ID</label>
                <input type="text" class="form-control" name="seriesID" placeholder="Series ID">
            </div>
            <button class="btn btn-primary" type="submit"  >Search</button>
        </form><br>

        uhh JSON should be here: {{data}}
    </div>
</body>
    <script type="text/javascript">
        $("#seriesID").submit(function (event) {
            $.post('/', $("#seriesID").serialize(), function (data) {
                 //data is the response from the backend
            });
            event.preventDefault();
        });
    </script>
</html>

1 个答案:

答案 0 :(得分:0)

使用res.render('home',{data}); 因为您的{{data}}未定义,所以它不打印任何内容 最好使用{{JSON.stringify(data)}}