带有Express的Node.js和PostgresSQL

时间:2018-12-27 08:54:30

标签: node.js json postgresql express

我已经编写了一个代码,使用express和NODE.js从postgres数据库中获取数据。数据库已与后端代码连接,但仍显示错误,如关系未退出。 请检查我得到的代码和错误:

var express = require('express');
var pg = require("pg");
var app = express();

var connectionString = "postgres://postgres:postgres@localhost:5432/testDatabase?currentSchema=testSchema";

app.get('/', function(req, res, next) {
    pg.connect(connectionString, function(err, client, done) {
        if (err) {
            console.log("Not able to get Connection " + err);
            res.status(400).send(err);
        } else {
            console.log("Connected.!");
        }

        const
        query = {
            // give the query a unique name
            name : 'fetch-user-details',
            text : 'SELECT * FROM loginTable',
        }

        client.query(query, function(err, result) {
            done(); // closing the connection;
            if (err) {
                console.log(err);
                res.status(400).send(err);
            }
            res.status(200).send(result.rows);
        });
    });
});

app.listen(4000, function() {
    console.log('Server is running.. on Port 4000');
});

,我得到的错误响应如下:

Server is running.. on Port 4000
Connected.!
{ error: relation "logintable" does not exist
    at Connection.parseE (C:\Users\sumit_srivastava\Desktop\Java_WorkSpace\SimpleNodeAppln\node_modules\pg\lib\connection.js:554:11)
    at Connection.parseMessage (C:\Users\sumit_srivastava\Desktop\Java_WorkSpace\SimpleNodeAppln\node_modules\pg\lib\connection.js:381:17)
    at Socket.<anonymous> (C:\Users\sumit_srivastava\Desktop\Java_WorkSpace\SimpleNodeAppln\node_modules\pg\lib\connection.js:117:22)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at Socket.Readable.push (_stream_readable.js:208:10)
    at TCP.onread (net.js:594:20)
  name: 'error',
  length: 120,
  severity: 'ERROR',
  code: '42P01',
  detail: undefined,
  hint: undefined,
  position: '15',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'src\\backend\\parser\\parse_relation.c',
  line: '986',
  routine: 'parserOpenTable' }

1 个答案:

答案 0 :(得分:1)

只需在我的Postgres上运行此数据库转储

CREATE SCHEMA "testSchema"; 
ALTER SCHEMA "testSchema" OWNER TO postgres; 
SET search_path = "testSchema", pg_catalog;
SET default_tablespace = '';
SET default_with_oids = false; 
CREATE TABLE "loginTable" ( "ID" numeric NOT NULL, "Name" text ); 
ALTER TABLE "loginTable" OWNER TO postgres; 

这是问题

将查询更改为此

 query = {
            // give the query a unique name
            name : 'fetch-user-details',
            text : `SELECT * FROM "testSchema".logintable`,
        }

您应该提及架构名称

品尝于

  • Ubuntu
  • postgres 10.6
  • pg:6.4.2
  • 节点v10.14.1