Javascript 从节点获取api数据

Javascript 从节点获取api数据,javascript,html,node.js,json,api,Javascript,Html,Node.js,Json,Api,我有odbc连接到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.l

我有odbc连接到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”}(还有更多行)

My 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>

函数getElement(id){
返回文档.getElementById(id);
}
取('http://localhost/query/colli')
.then(res=>res.json())
。然后((res)=>{
常数数据=res;
文件写入(数据)
getElement('name')。innerHTML='name:'+数据;
});

但我收到:

[对象对象],[对象对象]结果

请问我做错了什么?我想将数据从节点提取到HTML中


非常感谢您的时间:)

因为
data
是一个JSON对象,您不能执行
getElement('name')。innerHTML='name:'+data。您必须从对象中获取一个特定的键,该键指向您要查找的值。

根据您的console.log,调用get方法

  getElement('name').innerHTML = 'Name: ' + data[0].MATRK1 

由于数据是对象数组,我们需要通过其索引访问每个对象,每个对象中都有键MATRK1,因此我们使用数据[0]访问它。MATRK1

两件事:在节点端,简单地执行
res.json(result)
应该会发回一个json响应。在客户端html端,你不需要两个
。然后
res.json()
只需阅读
获取
响应,对其进行控制台,然后查看你需要从中获取哪些数据。谢谢,我已经修复了它,但是现在我收到了“Name:undefined”,根据下面的评论,你能用
控制台.log(数据)显示/更新问题吗
看起来像是?我回答如下:)但当我试图深入研究时:
getElement('name')。innerHTML='name:'+data.MATRK1Iam接收到“Name:undefined”尝试使用
console.log(data)
查看您在代码中使用它之前拥有的内容在获取答案时尝试类似的操作:
response.json()。然后(函数(data){})(索引):13未捕获(承诺中)类型错误:data.get不是位于(索引)的函数:13根据您的console.log(您说我正在某处),执行此console.log(数据[0])。由于您的数据是一个数组,或者尝试记录所有内容,data.forEach(i=>console.log(i)}forEach log:
{MATRK1:0000019863,FLG1K1:0000019863”FLG1K1:“S”\uu proto\uuu:Object
非常感谢:)现在我将它放入表中,它将得到解决:)