无法获取JavaScript连接到PostgresSql

时间:2019-04-27 12:53:03

标签: javascript node.js postgresql express

我制作了一个小型演示程序,以了解Web开发。 因此,我只想从本地服务器上的数据库中获取一些反馈。 但是由于某种原因,我无法建立连接

我已尝试遵循此指南: https://blog.logrocket.com/setting-up-a-restful-api-with-node-js-and-postgresql-d96d6fc892d8

这是我的querys.js:

const Pool = require('pg').Pool;
const pool = new Pool({
    user: 'barl',
    host: 'localhost',
    database: 'students',
    password: '123456',
    port: 5432,
});

const getUserById = (request, response) => {
    const id = parseInt(request.params.id);

    pool.query('SELECT * FROM students WHERE student_id = $1', [id], (error, results) => {
        if (error) {
            throw error;
        }
        response.status(200).json(results.rows);
    })
};

module.exports = {
    getUserById
};

这是我的server.js:

//Getting the express module
const express = require('express');
//Creating an App var that run the express method
const app = express();

const bodyParser = require('body-parser');

const db = require('./queries');

app.use(bodyParser.json());
app.use(
    bodyParser.urlencoded({
        extended: true,
    })
);

app.get('/students', function(req, res){
    db.getUserById;
});


//Setting the server to run on port blah blah
const server = app.listen(7000, () => {
    console.log(`Express running → PORT ${server.address().port}`);
});

然后,package.json:

{
  "name": "untitled3",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "npx pm2 start server.js --watch"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ejs": "^2.6.1",
    "express": "^4.16.4",
    "pg": "^7.10.0",
    "pm2": "^3.5.0",
    "body-parser": "latest"
  }
}

我的postgres DB在我的机器上正在运行并且工作正常,并且我可以看到信息。

但是当我将其放入浏览器时:

http://localhost:7000/students/1

我得到:

Cannot GET /students/1

我在这里想念什么?

1 个答案:

答案 0 :(得分:0)

这是因为您尚未定义尝试从浏览器访问的路由:

您正在尝试访问不存在的students/someid。另外,您还需要传递requestresponse对象

您可以将以下定义为:

app.get('/students/:id', function(req, res){
  db.getUserById(req, res);
});

:idnamed parameter,您可以通过req.params

访问

除了调用导出的db函数外,您的路由没有任何其他工作,不妨将其挂载为:

app.get('/students/:id', db.getUserById)