【发布时间】:2020-05-29 00:20:42
【问题描述】:
我有 odbc 连接到 Node JS 上的数据库。
var express = require('express');
var odbc = require('odbc');
var app = express();
var connectionString = 'Dsn=xxx;uid=xxx;pwd=xxx';
app.get('/query/:table', function (req, res) {
var table = req.params.table;
//console.log('User is accessing : ' + table);
var connection = odbc.connect(connectionString, (error, connection) => {
connection.query("SELECT * FROM " + table + "", (error, result) => {
if (error) { console.error(error) }
var json = JSON.stringify(result);
res.send(json);
});
});
});
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.listen(80, function () {
console.log('Application listening on port 80');
});
在 localhost/query/colli 我的输出是:
[ { "MATRK1": "0000019863", "FLG1K1": "S" }, { "MATRK1": "0000019864", "FLG1K1": "S" }](以及更多行)
我的 index.html 看起来像这样:
<script src="https://code.jquery.com/jquery-3.4.1.slim.js"
integrity="sha256-BTlTdQO9/fascB1drekrDVkaKd9PkwBymMlHOiG+qLI="
crossorigin="anonymous"></script>
<script>
function getElement(id) {
return document.getElementById(id);
}
fetch('http://localhost/query/colli')
.then(res => res.json())
.then((res) => {
const data = res;
document.write(data)
getElement('name').innerHTML = 'Name: ' + data;
});
</script>
<div>
<p id="name"></p>
</div>
<body>
</body>
但我收到了:
[object Object],[object Object]结果
请问我做错了什么?我想从 Node 中获取数据到 HTML。
非常感谢您的宝贵时间:)
【问题讨论】:
-
几件事:在节点端只需执行
res.json(result)应该会发回一个json响应。在客户端 html 端,您不需要两个.then和res.json()只需阅读fetch响应,对其进行控制台并查看您需要的数据。 -
谢谢你,我修好了,但现在我收到“名称:未定义”根据下面的评论
-
你能用
console.log(data)的样子显示/更新问题吗? -
我在下面回答:)
标签: javascript html node.js json api