首页 > 解决方案 > 尝试连接 Express 服务器以向 PostgreSQL 数据库发出 POST/GET 请求

问题描述

我四处寻找解决方案,但我似乎无法弄清楚这一点。我要做的是从 Express 服务器向 PostgreSQL 数据库发出 POST/GET 请求。

主.js:

var app = require('../app');
var debug = require('debug')('server:server');
var http = require('http');

var port = normalizePort(process.env.PORT || '8000');
app.set('port', port);

var server = http.createServer(app);

server.listen(port, () => {
  console.log(`Server is running on localhost:${port}`);
});
server.on('error', onError);
server.on('listening', onListening);

应用程序.js:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var helmet = require('helmet');

var indexRouter = require('./routes'); 

var app = express();
app.use(cors());
app.use(helmet());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);

module.exports = app;

routes.js(处理 api 请求)

router.post('/api/post/userprofiletodb', async (req, res, next) => {
    console.log(req);
    const values = [req.body.profile.nickname, req.body.profile.email, req.body.profile.email_verified];
    // ON CONFLICT DO NOTHING - prevents the user profile from being stored in db twice
    await pool.query(`INSERT INTO users(username, email, email_verified, date_created)
                VALUES($1, $2, $3, NOW() )
                ON CONFLICT DO NOTHING`, values,
                (q_err, q_res) => {
                    if (q_err) return next(q_err);
                    console.log(q_res);
                    res.json(q_res.rows);
                })
})

router.get('/api/get/userprofilefromdb', async (req, res, next) => {
    console.log(req);
    const email = String(req.query.email);
    await pool.query(`SELECT * FROM users WHERE email=$1`, [email],
    (q_err, q_res) => {
        if (q_err) return next(q_err);
        res.json(q_res.rows);
    })
})

db.js:

const { Pool } = require('pg');
const pool = new Pool({
    user: 'postgres',
    host: 'localhost',
    database: 'mydb',
    password: 'mypassword',
    post: 5432
});

module.exports = pool;

React 代码(Redux 的 Action Creators):

export const setDbProfile = (profile) => async(dispatch) => {
    const response = await axios.post('http://localhost:8000/api/post/userprofiletodb', profile);
    dispatch({ type: SET_DB_PROFILE, payload: response.data });
    console.log(response);
    history.replace('/');
}

export const getDbProfile = (profile) => async(dispatch) => {
    const data = profile;
    console.log('getDbProfile', profile);
    const response = await axios.get('http://localhost:8000/api/get/userprofilefromdb',
        {
            params: {
                email: data.profile.email
            }        
        }
    )
    dispatch({ type: GET_DB_PROFILE, payload: response.data });
    history.replace('/');

这是我的思考过程: - 我在http://localhost:8000
上设置了我的 Express 服务器,并且我的 React 应用程序在http://localhost:3000上运行(我已经在 package.json 文件中包含了一个代理) . - 当调用动作创建者时,它首先向我的 Express 服务器所在的http://localhost:8000发出一个 post 请求。 - Express 服务器看到这一点并向存储在 localhost:5432 上的 PostgreSQL 数据库发出请求。

但是,我收到此错误....

POST /api/post/userprofiletodb 500 182.558 ms - 250
Error: connect ECONNREFUSED 127.0.0.1:5432
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
GET /api/get/userprofilefromdb?email=dasfdfasfdf@gmail.com 500 52.541 ms - 250
Error: connect ECONNREFUSED 127.0.0.1:5432
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)

我认为我的 PostgreSQL 数据库可能存在问题。我如何设置它是通过打开 SQL Shell (psql) 并执行以下操作: - CREATE DATABASE mydb;
- \c mydb
- 创建表用户(...);
- 创建表格帖子(...);
- 创建表评论(...);

不太确定如何解决这个问题......任何指导将不胜感激!干杯。

更新:
当我运行命令时

netstat -na

我没有看到,127.0.0.1.5432 根本没有列出...这是否意味着我的数据库没有正确设置?

运行 SQL Shell (psql)

x-MacBook-Air:~ x$ /Library/PostgreSQL/12/scripts/runpsql.sh; exit
Server [localhost]: 
Database [postgres]: 
Port [5000]: 5432
Username [postgres]: 
psql: error: could not connect to server: could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?

Press <return> to continue...

标签: node.jsreactjspostgresqlexpressreact-redux

解决方案


推荐阅读