首页 > 解决方案 > 无法在 html 中呈现 JSON - node.js

问题描述

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

服务器.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>

标签: javascripthtmljsonnode.jsexpress

解决方案


使用res.render('home',{data}); ,因为你{{data}}是未定义的,这就是为什么它不打印任何更好使用的东西{{JSON.stringify(data)}}


推荐阅读