javascript - 无法在 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>
解决方案
使用res.render('home',{data});
,因为你{{data}}
是未定义的,这就是为什么它不打印任何更好使用的东西{{JSON.stringify(data)}}
推荐阅读
- html - chrome扩展弹出窗口是否可以成为页面的一部分?
- javascript - 具有初始值 OnFocus 的自动完成搜索框
- google-drive-api - 在网站中嵌入谷歌文档:用户评论在 Chrome 中始终是匿名的(但在 Firefox 中有效)
- javascript - V-for 手风琴中的动态类
- reactjs - Stripe checkout 在我的 react + strapi 应用程序中不起作用 - this.props.stripe.createToken() 出现“未定义”错误
- c++ - char8_t * 的 printf() 格式字符是什么?
- c - 如何从 Gstreamer 管道中逐帧获取视频流?(没有 OpenCV)
- sqlite - 如何为 SQLite 的 PRAGMA application_id 选择一个幻数
- javascript - 带有关闭按钮的弹出式渲染,但单击时不起作用?
- c# - Access数据库插入不成功