I'm now learning Node.js and Express, and want to use mysql
module to render multiple unique pages, so instead of writing out var connection=mysql.createConnection({user:'root', password: 'root'...etc})
line on every file located under routes
directory, I'm sure it's better off to just call my own mysql config file on each routing file.
However, where should I put the config file on Express hierarchy and how can I call the file from within each routing file? I know all images, style sheets, and javascript files should be located within each specific directory under public
directory, but I don't know where to put all the other files that are intended to be accessed from routing files.
I also want to know whether all of my files, ranging from main app.js
to files under routes
directory to files under public
directory, etc... can be found by users once I publicize this web application on the Web. If it's the case, then I think I should not put database config file on directories that clients can access to...right? In other words, I want to make sure which files can be accessed to by clients and which cannot in order to avoid security attacks.
The configuration files are located in the default config directory. The location can be overriden with the NODE_CONFIG_DIR environment variable. The NODE_ENV environment variable contains the name of our application's deployment environment; it is development by default.
Create a config directory and add a config/default. json file to it. This will be the default config file and will contain all your default environment variables. We'll access it in our app by importing config and using the get method to access the variables.
To connect a Node. js application to MongoDB, we have to use a library called Mongoose. mongoose. connect("mongodb://localhost:27017/collectionName", { useNewUrlParser: true, useUnifiedTopology: true });
To answer your first question "Where to put the config file?": This is a little bit personnal. Put it to the root of your application.
config.js:
module.exports = {
database:{
host: ""
user: "..."
}
}
then you include it in you app.js:
app.js:
...
config = require("./config");
db = config.database;
var connection=mysql.createConnection({user:db.user, ...})
Note that you might want two config file, one in you version control and one private to the machine. Different developers might have different database access for example. But I don't think you have to worry about that for now.
For your second question "Are all my files public?": No, only the file you specify as static (with the express middleware) will be served.
app.js:
...
// Exposes the public folder
app.use(express.static(__dirname + '/public'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With