简体   繁体   中英

Proper use of app.set in express?

I am currently following https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens . However, I do not understand the need for ...

app.set('superSecret', config.secret);

... when you could just continue using config.secret . Can someone kindly explain this to me? Much appreciated.

This simply allows you to access your values via app.settings.superSecret and nothing else.

The good thing about this is, you won't have to keep importing your config object to every file! You can simply grab the value straight from app.settings .

It really comes down to personal choice.

I recommend you read up on the docs over at express: expressjs.com/en/4x/api.html

The reason for a global config file is so you can use specific environments and hide the secret data from say github or bitbucket (some sort of version control service). You wouldn't be uploading your secret details to github, bitbucket, or any other similar service. When I say environments I mean production, development, local, and etc. You could have a function inside your config file that returns a specific objects. Eg

var env = {
  production: {
  ... env vars
  },
  local: {
  ... local vars
  }
}

export default env["production"]; // You would change something here or

Note this is a very basic example of what you could do to change your environment variables. You can simply change env["production"] to env["local"] to swap your environment.

use express session

server.js

var config = require('./config');
var session = require('express-session');
 app.use(session({
    saveUninitialized: true,
    resave: true,
    secret: config.sessionSecret
 }));

config.js

module.exports = {
 sessionSecret: "very-secret" // or if loading from your .env **sessionSecret:process.env.SECRET**
}

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