简体   繁体   English

无法使用 knex.js 连接到 heroku psql 数据库

[英]Unable to connect to heroku psql database using knex.js

I am unable to connect to psql database on heroku through backend in express.js .What can be the reason?我无法通过 express.js 中的后端连接到 heroku 上的 psql 数据库。可能是什么原因? Plz someone answer !请有人回答

server.js code is: server.js 代码是:

const { handleRegister } = require('./Controllers/Register');
const knex = require('knex');
const db = knex({
    client: 'pg',
    connection: {
      connectionString : process.env.DATABASE_URL,
      ssl: true
    }
 });
app.post('/register', (req,res) => {
    handleRegister(req,res,db,bcrypt);  
})

And the code inside register.js is: register.js 里面的代码是:

const saltRounds = 10;
const handleRegister = (req,res,db,bcrypt) => {
    const {firstname, lastname, email, password} = req.body;
    if(!email || !firstname || !lastname || !password){
        return res.status(400).json("Incorrect from submission!");
    }
    bcrypt.genSalt(saltRounds, function(err, salt) {
        bcrypt.hash(password, salt, null , function(err, hash) {
            db.transaction(trx => {
                trx.insert({
                    hash: hash,
                    email: email
                })
                .into("login")
                .returning("email")
                .then(mail => {
                    return trx("users")
                    .returning('*')
                    .insert({
                        email: mail[0],
                        firstname: firstname,
                        lastname: lastname,
                        name: firstname + " " + lastname,
                        joined: new Date()
                    })
                    .then(user => {
                        res.json(user[0]);
                    }).catch(err => {res.json("Unable to Register!")});
                })
                .then(trx.commit)
                .catch(trx.rollback)
            })
            .catch(err => {
                res.json("Error while Registring user!");
            })  
        }); 
    });
}

I'm getting response "Error while Registring user!",But I successfully connected to the database using cmd, here is ss:我收到响应“注册用户时出错!”,但我使用 cmd 成功连接到数据库,这里是 ss:

Screenshot of Database connected successfully数据库连接成功截图

Can someone tell me how to fix this issue???有人能告诉我如何解决这个问题吗???

It may be the fact that you are using free version of Heroku.可能是因为您使用的是免费版 Heroku。 Setting ssl to将 ssl 设置为
ssl: { rejectUnauthorized: false } worked for me when I had similar problem. ssl: { rejectUnauthorized: false }当我遇到类似问题时对我ssl: { rejectUnauthorized: false } However, this is not safe for production use!但是,这对于生产使用来说并不安全! Use it only in the case of personal project.仅在个人项目的情况下使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM