简体   繁体   中英

Fetch api data from Node

I have odbc connection to database on 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 :

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

My index.html looks like this :

<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

What am i doing wrong please? I want to fetch data from Node into HTML.

Thanks very much for your time :)

As data is a JSON object you can't do 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

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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