Setting up the express web server – Part 4
Next we will write some server-side javascript codes to func on as a web server that listen on port 5000. (Note: the
default port for HTTP and HTTPS is 80 and 443 respec vely)
server.js
Run the server.js code and browse to the URL
The server.js file sets up a basic Express server that interacts with a MongoDB database. It performs several
tasks to initialize and configure the application:
Importing Modules: The script starts by importing necessary modules:
mongoose: Used for interacting with MongoDB.
express: A web application framework for Node.js used to create routes and handle HTTP requests.
path: A core Node.js module that provides utilities for working with file and directory paths.
Loading Environment Variables: The .env file is loaded using the dotenv module, which allows environment
variables to be easily accessed throughout the application. This setup ensures sensitive information like
database connection strings are kept secure.
Importing Router Module: The userRouter module is imported from the ./routes/userRouter file. This module
contains routes specific for user-related operations.
Setting Mongoose Options: The mongoose.set('strictQuery', true); line ensures that Mongoose uses strict
query syntax, which helps in catching potential errors related to incorrect queries or schema mismatches.
Connecting to MongoDB Database: The mongoose.connect(process.env.DB_CONNECT) line attempts to
connect the server to a MongoDB database using a connection string provided as an environment variable
(DB_CONNECT). If the connection is successful, it logs 'MongoDB connected...' to the console.
Creating Express Application: An instance of the Express application is created using const app = express();.
Setting Server Port: The server port is set either from the environment variable PORT or defaults to 3000 if not
provided. This allows the server to listen on the specified port for incoming requests.
Using Middleware:
app.use(express.json()): This middleware parses incoming JSON payloads, making them accessible in req.body.
app.use(express.urlencoded({ extended: true })): This middleware parses incoming URL-encoded bodies,
allowing complex data structures to be sent through the HTTP request.
Serving Static Files: The app.use(express.static(path.join(__dirname, 'public'), { index: 'index.html' })) line
configures Express to serve static files from the public directory. It also sets the default index file for root URL
requests to index.html.
Starting Server: Finally, the server is started on the specified port using app.listen(PORT, () => { ... });. Upon
successful startup, it logs a message indicating the server is running and provides a URL to access it.
This setup forms the foundation of a Node.js Express application that interacts with a MongoDB database,
handling user-related operations through routing.