无法从本地节点应用程序以sequelize连接到heroku postgresql数据库
我试图从Sequelize的本地nodejs应用程序连接到Heroku postgresql数据库。 我遵循这两个指南,一切都在英雄服务器端的工作完全正常,但我的节点应用程序将不会连接到heroku当我在我的Mac本地运行它。
- http://sequelizejs.com/articles/heroku
- https://devcenter.heroku.com/articles/connecting-to-heroku-postgres-databases-from-outside-of-heroku
以下是我如何启动本地应用程序:
DATABASE_URL=$(heroku config:get DATABASE_URL) nodemon
得到我:
Sequelize: Unable to connect to the database:
但是我通过这样做得到正确的URL:
echo $(heroku config:get DATABASE_URL)
这些命令工作正常:
heroku pg:psql psql $(heroku config:get DATABASE_URL)
这是我的nodejs代码:
var match = process.env.DATABASE_URL.match(/postgres:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/) sequelize = new Sequelize(match[5], match[1], match[2], { dialect: 'postgres', protocol: 'postgres', port: match[4], host: match[3], logging: false }) sequelize .authenticate() .complete(function(err) { if (!!err) { log('Sequelize: Unable to connect to the database:', err); } else { http.listen(process.env.PORT || config.server.port, function(){ log('Web server listening on port '+process.env.PORT || config.server.port); }); } });
我试图添加native: true
对sequelize选项,但是我得到:
/Users/clement/Projets/XMM/node_modules/sequelize/lib/sequelize.js:188 throw new Error('The dialect ' + this.getDialect() + ' is not supported. ^ Error: The dialect postgres is not supported. (Error: Please install postgres package manually) at new module.exports.Sequelize (/Users/clement/Projets/XMM/node_modules/sequelize/lib/sequelize.js:188:13) at Object.<anonymous> (/Users/clement/Projets/XMM/server.js:17:14) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:929:3
即使在做:
npm install pg npm install -g pg brew install postgresql
这是顺便说一句:
var pg = require('pg'); pg.connect(process.env.DATABASE_URL+'?ssl=true', function(err, client, done) { if (err) return console.log(err); client.query('SELECT * FROM pg_catalog.pg_tables', function(err, result) { done(); if(err) return console.error(err); console.log(result.rows); }); });
但我宁愿使用Sequelize。
好的,通过浏览sequelize源代码find答案: https : //github.com/sequelize/sequelize/blob/master/lib/dialects/postgres/connection-manager.js#L39
要为PG连接激活SSL,你不需要native: true
或者ssl: true
但是dialectOptions.ssl: true
所以最后的工作是:
var match = process.env.DATABASE_URL.match(/postgres:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/) sequelize = new Sequelize(match[5], match[1], match[2], { dialect: 'postgres', protocol: 'postgres', port: match[4], host: match[3], logging: false, dialectOptions: { ssl: true } });
您不再需要parsingDATABASE_URL envvariables,还有一个接受连接URL的Sequelize构造器:
sequelize = new Sequelize(process.env.DATABASE_URL, { dialect: 'postgres', protocol: 'postgres', dialectOptions: { ssl: true } });