首页 > 解决方案 > 无法使用 NodeJS 从 postgres 获取数据到 DataTables

问题描述

我正在尝试使用 Postgres 中的数据填充 DataTables 行。到目前为止,这是我的 JavaScript 和 HTML 文件。但我收到错误“加载资源失败:服务器响应状态为 404(未找到)”。关于为什么浏览器无法获取文件的任何建议?我在 NodeJS 中使用 express。

var express = require('express');
var postgres = require('./postgres')

var app = express();

app.use(express.static(__dirname + '/public')); 

const result = postgres.migration();
console.log(result)

var port = 8000; 
app.listen(port);

console.log('server on' + port);

const pg = require('pg');

const cs = 'postgres://postgres:123456@localhost:5432/lsef';

const client = new pg.Client(cs);

client.connect();

const query = {
    text: 'SELECT * FROM profile',
    rowMode: 'array'
};

client.query(query).then(res => {

    const data = res.rows;

    console.log(data);
    return data
    // data.forEach(row => {
    //     console.log(`Id: ${row[0]} Name: ${row[1]} Age: ${row[2]} Contact: ${row[3]}`);
    // })
}).finally(() => {
    client.end()
});
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css">
    <script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div class="container" >
    <table border="1px solid black" id="example">
        <thead>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Contact</th>
        </thead>
        <tbody style=text-align:center>
        <script>
            $(document).ready(function(){
                $("#example").DataTable({
                    "ajax":{
                        'url':'getData.js',
                        'type':'POST',                                                
                        "dataSrc":"",
                    },
                    "columns": [
                        { "data": 'id'},
                        { "data": "name" },
                        { "data": "email" },
                        { "data": "contact" }
                    ],
                    "pagingType":"full_numbers",
                    "dom" : "fltip",
                    "stateSave":true,
                    "lengthMenu" : [[5,10,15,-1],[5,10,15,'ALL']],
                    "order":[[0,"asc"]],
                });
            });
        </script>
        </tbody>
    </table>
</div>
</body>
</html>

标签: javascripthtmlnode.jspostgresqldatatables

解决方案


推荐阅读