0

我正在构建一个简单的后端服务器,我之前使用 heroku 部署了它。除了部署服务器,我还创建了一个包含所有我需要的表的 heroku postgres 数据库。当我尝试使用 knex 将数据库连接到服务器时出现问题;即使它在本地端口中运行时可以工作,但如果我使用我的 heroku postgres 数据库,我在尝试注册时会在前端获取错误。在这里,我分享了我的服务器代码以及 package.json 和 heroku 日志。希望提供的信息是足够的,并且事先,我非常感谢我能得到的任何帮助。

const express = require('express');
const bodyParser = require('body-parser'); 
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const knex = require('knex');

const db = knex({
    client: 'pg',
    connection: {
        connectionString: process.env.DATABASE_URL,
        ssl: true,
    }
});

const app = express();

app.use(cors())
app.use(express.json()); 


app.get('/', (req, res) => {
    res.send('it is working!');
})

app.post('/signin', (req, res) => {
    if (!req.body.email || !req.body.password) {
        return res.status(400).json('Incorrect Form Submission');
    }
    db.select('email', 'hash').from('login')
        .where('email', '=', req.body.email)
        .then(data => {
            const isValid = bcrypt.compareSync(req.body.password, data[0].hash);
            if (isValid) {
                return db.select('*').from('users')
                    .where('email', '=', req.body.email)
                    .then(user => {
                        res.json(user[0])
                    })
                    .catch(err => res.status(400).json('unable to get user'))
            } else {
                res.status(400).json('Invalid Email or Password')
            }
        })
        .catch(err => res.status(400).json('Invalid Email or Password'))
})

app.post('/register', (req, res) => {
    const { email, name, password } = req.body;
    if (!email || !name || !password) {
        return res.status(400).json('Incorrect Form Submission');
    }
    const hash = bcrypt.hashSync(password);
    db.transaction(trx => {
        trx.insert({
            hash: hash,
            email: email
        })
            .into('login')
            .returning('email')
            .then(loginEmail => {
                trx('users')
                    .returning('*')
                    .insert({
                        email: loginEmail[0].email,
                        name: name,
                        joined: new Date()
                    })
                    .then(user => {
                        res.json(user[0]);
                    })
            })
            .then(trx.commit)
        .catch(trx.rollback)
        })
    .catch(err => res.status(400).json('unable to register'))
})

app.get('/profile/:id', (req, res) => {
    const { id } = req.params;
    db.select('*').from('users').where({ id })
        .then(user => {
            if (user.length) {
                res.json(user[0])
            } else {
                res.status(400).json('Not found')
            }
        })
        .catch(err => res.status(400).json('error getting user'))
})

app.listen(process.env.PORT || 3001, () => {
    console.log(`app is running on port ${process.env.PORT}`);
})

//package.json://

{
  "name": "smart-brain-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt-nodejs": "^0.0.3",
    "body-parser": "^1.19.1",
    "cors": "^2.8.5",
    "express": "^4.17.2",
    "knex": "^1.0.1",
    "pg": "^8.7.1"
  }
}

//heroku logs://

2022-02-08T23:23:28.060879+00:00 heroku[web.1]: Process exited with status 143
2022-02-08T23:23:28.873764+00:00 heroku[web.1]: Starting process with command `npm start`
2022-02-08T23:23:29.905650+00:00 app[web.1]: 
2022-02-08T23:23:29.905693+00:00 app[web.1]: > smart-brain-api@1.0.0 start
2022-02-08T23:23:29.905694+00:00 app[web.1]: > node server.js
2022-02-08T23:23:29.905694+00:00 app[web.1]: 
2022-02-08T23:23:30.153048+00:00 app[web.1]: app is running on port 54976
2022-02-08T23:23:30.554379+00:00 heroku[web.1]: State changed from starting to up
2022-02-08T23:24:01.377280+00:00 heroku[router]: at=info method=OPTIONS path="/register" host=smart-brain-bodypix.herokuapp.com request_id=55d207b6-9861-4b69-b082-02a6bb64e54a fwd="69.194.63.134" dyno=web.1 connect=0ms service=7ms status=204 bytes=301 protocol=https
2022-02-08T23:24:01.843444+00:00 heroku[router]: at=info method=POST path="/register" host=smart-brain-bodypix.herokuapp.com request_id=e7591f96-ddd8-42cc-aa83-8b49d1155981 fwd="69.194.63.134" dyno=web.1 connect=0ms service=296ms status=400 bytes=268 protocol=https
2022-02-08T23:39:00.932582+00:00 heroku[router]: at=info method=OPTIONS path="/register" host=smart-brain-bodypix.herokuapp.com request_id=e7e9595c-0d7c-4ff0-b4cd-02aa716e6a77 fwd="69.194.63.134" dyno=web.1 connect=0ms service=2ms status=204 bytes=301 protocol=https
2022-02-08T23:39:01.252176+00:00 heroku[router]: at=info method=POST path="/register" host=smart-brain-bodypix.herokuapp.com request_id=b4a14eec-3bb7-41f7-9299-c5a7c41fb5f2 fwd="69.194.63.134" dyno=web.1 connect=0ms service=259ms status=400 bytes=268 protocol=https
2022-02-08T23:39:01.746491+00:00 heroku[router]: at=info method=POST path="/register" host=smart-brain-bodypix.herokuapp.com request_id=9cde7cd8-6d98-4432-bb83-3407a35114cb fwd="69.194.63.134" dyno=web.1 connect=0ms service=256ms status=400 bytes=268 protocol=https

4

1 回答 1

0

尝试使用 knex 更改用于连接 postgres 数据库的代码,如下所示,

import knex, { Config } from "knex";
// @ts-ignore
import knexStringcase from "knex-stringcase";

import { db, isDev } from "../config";

const config = knexStringcase({
  debug: isDev,
  client: "pg",
  connection: {
    connectionString: db,
    ssl: {
      rejectUnauthorized: false,
    },
  },
  searchPath: ["public"],
  // pool: isDev ? { max: 4 } : { min: 4 },
  asyncStackTraces: true,
} as Config) as Config;

export default knex(config);

对于与配置相关的查询,请查看:https ://dpletzke.medium.com/configuring-free-heroku-node-postgresql-hosting-with-knex-b0e97a05c6af

于 2022-02-20T15:26:48.863 回答