简体   繁体   中英

Node/Express app— how to change connection string (node-postgress) based on localhost vs. remote server

I have a node application running an express server that is deployed on heroku. I'm using a postgres database (node-postgres) and currently have the application configured with a connection string for the remote database.

I created a local version of the database, and I would like to configure the application to use a different connection string when running the app on localhost.

I need to somehow detect what server I'm on and then put the conString in an if/else kind of statement. Any ideas or examples? I was having trouble finding the right solution.

For that you should use the standard NodeJS environment variable - NODE_ENV .

It should be set to development on your local machine. And on your production server it is usually defaulted to production , as it is on Heroku: NODE_ENV=production

Then you can access it from your app via process.env.NODE_ENV . This will tell you in which environment your app is running, and thus which of the two connections you should use.

I would recommend konfig . Create a file named database.js in a folder named config, include it from your app and konfig does the environment switching.

Example

config/database.json:

{
  "development": {
    "postgresql": {
      "connection_string": "postgres://user:pass@localhost/development"
    }
  },
  "production": {
    "postgresql": {
      "connection_string": "postgres://user:pass@ec2.compute-1.amazonaws.com/sdfk23jf"
    }
  }
}

app.js:

...
var config = require('konfig')().database.connection_string;
...

Use NODE_ENV when you run the server on the command-line, ie

NODE_ENV=production node app.js

and konfig will automatically do the switching, I think it uses "development" by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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