gpt4 book ai didi

javascript - 无法让 JavaScript 连接到 Postgresql

转载 作者:行者123 更新时间:2023-11-29 13:40:38 25 4
gpt4 key购买 nike

我正在制作一个小的演示程序来学习网络开发。所以我只想从本地主机服务器上的数据库中获得一些反馈。但是由于某种原因,我无法连接

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

这是我的 queries.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 数据库正在我的机器上运行并完美运行,我可以看到信息。

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

http://localhost:7000/students/1

我得到:

Cannot GET /students/1

我在这里错过了什么?

最佳答案

这是因为您还没有定义您尝试从浏览器访问的路由:

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

您可以将其定义为:

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

:id 是一个命名参数,您可以通过req.params

访问它

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

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

关于javascript - 无法让 JavaScript 连接到 Postgresql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55880733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com