16.3 C
Москва
16.07.2026

tags from the preceding column and the closing tags for the row, container, and HTML document. Remember to leave these tags in place as you add the following code to create the column:
~/node_project/views/getshark.html

Here you are using EJS template tags and the forEach() method to output each value in your sharks collection, including information about the most recently added shark.

The entire container with all three columns, including the column with your sharks collection, will look like this when finished:

~/node_project/views/getshark.html

. 
Sawshark

Sammy the Shark

    Name:

    Character: ); %>

Save and close the file when you are finished editing.

In order for the application to use the templates you’ve created, you will need to add a few lines to your app.js file. Open it again:

Above where you added the express.urlencoded() function, add the following lines:

~/node_project/app.js

. app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.use(express.urlencoded( extended: true >)); app.use(express.static(path)); . 

The app.engine method tells the application to map the EJS template engine to HTML files, while app.set defines the default view engine.

Your app.js file should now look like this:

~/node_project/app.js

const express = require('express'); const app = express(); const router = express.Router(); const db = require('./db'); const path = __dirname + '/views/'; const port = 8080; router.use(function (req,res,next)  console.log('/' + req.method); next(); >); router.get('/',function(req,res) res.sendFile(path + 'index.html'); >); router.get('/sharks',function(req,res) res.sendFile(path + 'sharks.html'); >); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.use(express.urlencoded( extended: true >)); app.use(express.static(path)); app.use('/', router); app.listen(port, function ()  console.log('Example app listening on port 8080!') >) 

Now that you have created views that can work dynamically with user data, it’s time to create your project’s routes to bring together your views and controller logic.

Step 6 — Creating Routes

The final step in bringing the application’s components together will be creating routes. We will separate our routes by function, including a route to our application’s landing page and another route to our sharks page. Our sharks route will be where we integrate our controller’s logic with the views we created in the previous step.

First, create a routes directory:

Next, open a file called index.js in this directory:

This file will first import the express , router , and path objects, allowing us to define the routes we want to export with the router object, and making it possible to work dynamically with file paths. Add the following code at the top of the file:

~/node_project/routes/index.js

const express = require('express'); const router = express.Router(); const path = require('path'); 

Next, add the following router.use function, which loads a middleware function that will log the router’s requests and pass them on to the application’s route:

~/node_project/routes/index.js

. router.use (function (req,res,next)  console.log('/' + req.method); next(); >); 

Requests to our application’s root will be directed here first, and from here users will be directed to our application’s landing page, the route we will define next. Add the following code below the router.use function to define the route to the landing page:

~/node_project/routes/index.js

. router.get('/',function(req,res) res.sendFile(path.resolve('views/index.html')); >); 

When users visit our application, the first place we want to send them is to the index.html landing page that we have in our views directory.

Finally, to make these routes accessible as importable modules elsewhere in the application, add a closing expression to the end of the file to export the router object:

~/node_project/routes/index.js

. module.exports = router; 

The finished file will look like this:

~/node_project/routes/index.js

const express = require('express'); const router = express.Router(); const path = require('path'); router.use (function (req,res,next)  console.log('/' + req.method); next(); >); router.get('/',function(req,res) res.sendFile(path.resolve('views/index.html')); >); module.exports = router; 

Save and close this file when you are finished editing.

Next, open a file called sharks.js to define how the application should use the different endpoints and views we’ve created to work with our user’s shark input:

At the top of the file, import the express and router objects:

~/node_project/routes/sharks.js

const express = require('express'); const router = express.Router(); 

Next, import a module called shark that will allow you to work with the exported functions you defined with your controller:

~/node_project/routes/sharks.js

const express = require('express'); const router = express.Router(); const shark = require('../controllers/sharks'); 

Now you can create routes using the index , create , and list functions you defined in your sharks controller file. Each route will be associated with the appropriate HTTP method: GET in the case of rendering the main sharks information landing page and returning the list of sharks to the user, and POST in the case of creating a new shark entry:

~/node_project/routes/sharks.js

. router.get('/', function(req, res) shark.index(req,res); >); router.post('/addshark', function(req, res)  shark.create(req,res); >); router.get('/getshark', function(req, res)  shark.list(req,res); >); 

Each route makes use of the related function in controllers/sharks.js , since we have made that module accessible by importing it at the top of this file.

Finally, close the file by attaching these routes to the router object and exporting them:

~/node_project/routes/index.js

. module.exports = router; 

The finished file will look like this:

~/node_project/routes/sharks.js

const express = require('express'); const router = express.Router(); const shark = require('../controllers/sharks'); router.get('/', function(req, res) shark.index(req,res); >); router.post('/addshark', function(req, res)  shark.create(req,res); >); router.get('/getshark', function(req, res)  shark.list(req,res); >); module.exports = router; 

Save and close the file when you are finished editing.

The last step in making these routes accessible to your application will be to add them to app.js . Open that file again:

Below your db constant, add the following import for your routes:

~/node_project/app.js

. const db = require('./db'); const sharks = require('./routes/sharks'); 

Next, replace the app.use function that currently mounts your router object with the following line, which will mount the sharks router module:

~/node_project/app.js

. app.use(express.static(path)); app.use('/sharks', sharks); app.listen(port, function ()  console.log("Example app listening on port 8080!") >) 

You can now delete the routes that were previously defined in this file, since you are importing your application’s routes using the sharks router module.

The final version of your app.js file will look like this:

~/node_project/app.js

const express = require('express'); const app = express(); const router = express.Router(); const db = require('./db'); const sharks = require('./routes/sharks'); const path = __dirname + '/views/'; const port = 8080; app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.use(express.urlencoded( extended: true >)); app.use(express.static(path)); app.use('/sharks', sharks); app.listen(port, function ()  console.log('Example app listening on port 8080!') >) 

Save and close the file when you are finished editing.

You can now run tree again to see the final structure of your project:

Your project structure will now look like this:

Output
├── Dockerfile ├── README.md ├── app.js ├── controllers │ └── sharks.js ├── db.js ├── models │ └── sharks.js ├── package-lock.json ├── package.json ├── routes │ ├── index.js │ └── sharks.js └── views ├── css │ └── styles.css ├── getshark.html ├── index.html └── sharks.html

With all of your application components created and in place, you are now ready to add a test shark to your database!

If you followed the initial server setup tutorial in the prerequisites, you will need to modify your firewall, since it currently only allows SSH traffic. To permit traffic to port 8080 run:

Start the application:

Next, navigate your browser to http:// your_server_ip :8080 . You will see the following landing page:

Application Landing Page

Click on the Get Shark Info button. You will see the following information page, with the shark input form added:

Shark Info Form

In the form, add a shark of your choosing. For the purpose of this demonstration, we will add Megalodon Shark to the Shark Name field, and Ancient to the Shark Character field:

Filled Shark Form

Click on the Submit button. You will see a page with this shark information displayed back to you:

Shark Output

You will also see output in your console indicating that the shark has been added to your collection:

Output
Example app listening on port 8080!

If you would like to create a new shark entry, head back to the Sharks page and repeat the process of adding a shark.

You now have a working shark information application that allows users to add information about their favorite sharks.

Conclusion

In this tutorial, you built out a Node application by integrating a MongoDB database and rewriting the application’s logic using the MVC architectural pattern. This application can act as a good starting point for a fully-fledged CRUD application.

For more information on working with MongoDB, please see our library of tutorials on MongoDB.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Tutorial Series: From Containers to Kubernetes with Node.js

In this series, you will build and containerize a Node.js application with a MongoDB database. The series is designed to introduce you to the fundamentals of migrating an application to Kubernetes, including modernizing your app using the 12FA methodology, containerizing it, and deploying it to Kubernetes. The series also includes information on deploying your app with Docker Compose using an Nginx reverse proxy and Let’s Encrypt.

Browse Series: 7 articles

Читать:
Где производят volvo s90

Похожие записи

Инструмент вставить находится на какой панели

admin

Как устроен javascript pdf

admin

Мазда что означает логотип

admin