简体   繁体   English

从 Node 获取 api 数据

[英]Fetch api data from Node

I have odbc connection to database on Node JS.我有 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');
});

on localhost/query/colli my output is :在 localhost/query/colli 上,我的输出是:

[ { "MATRK1": "0000019863", "FLG1K1": "S" }, { "MATRK1": "0000019864", "FLG1K1": "S" }] (and a lot of more rows) [ { "MATRK1": "0000019863", "FLG1K1": "S" }, { "MATRK1": "0000019864", "FLG1K1": "S" }] (还有很多行)

My index.html looks like this :我的 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>

But i am receiving :但我收到:

[object Object],[object Object] result [object Object],[object Object]结果

What am i doing wrong please?请问我做错了什么? I want to fetch data from Node into HTML.我想从 Node 获取数据到 HTML 中。

Thanks very much for your time :)非常感谢你花时间陪伴 :)

As data is a JSON object you can't do getElement('name').innerHTML = 'Name: ' + data;由于data是一个 JSON 对象,你不能执行getElement('name').innerHTML = 'Name: ' + data; . . You will have to get a specific key from your object leading to the value you are looking for.您必须从您的对象中获取一个特定的键,从而获得您正在寻找的值。

depending on your console.log, call the get method根据您的 console.log,调用 get 方法

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

since data is array of objects, we need to access each object by its index, and each object has the key MATRK1 in it, so we access it using data[0].MATRK1由于 data 是对象数组,我们需要通过索引访问每个对象,每个对象都有键 MATRK1,所以我们使用 data[0].MATRK1 访问它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM