Node.js 它是一个运行时环境,允许您在服务器端运行 JavaScript 代码以构建服务器端应用程序。它非常适合创建快速且可扩展的应用程序。
在本文中,我将以一个简单的事件管理应用程序为例,向您展示如何使用 Node.js、Express.js 和 MongoDB 构建应用程序。
最后,您将了解如何设置 Node.js 项目、使用 Express.js 创建服务器、显示带有嵌入式 JavaScript 的动态页面,以及连接到 MongoDB 数据库来处理数据。
首先,您需要下载并安装 Node.js。然后您可以通过运行以下命令来验证安装:node -v 和 npm -v。
为您的项目创建一个新目录。然后在终端中使用 npm 初始化项目: npm init -y。
mkdir event-app cd event-app npm init -y
运行 npm init -y 创建 package.json 文件,如上所示。这个文件至关重要。它存储并跟踪您的应用程序所需的所有第三方库(依赖项)。
要设置服务器,请创建一个名为 server.js 或 app.js 的文件。这些都是常见的名字。它们因其描述性而被使用。但是,您可以根据自己的喜好命名该文件。
server.js 文件将用于创建一个服务器,该服务器将用于管理、控制和路由到我们应用程序中的必要页面。
Express.js 是 Node.js 的流行 Web 应用程序框架,也是我们在应用程序中使用的第三方库。
Express 简化了 HTTP 请求的各种路由的处理和定义。它使您能够管理应用程序的路由并将其连接到服务器。
通过在终端中运行以下命令来安装 Express.js:
npm install express
在您的 server.js 文件中需要 Express。
const express = require('express')
初始化 Express,以便您可以在应用程序中使用它。
const app = express()
创建路由路径来获取HTTP请求。
//routing path app.get('/', (req, res) => { res.send('Hello World!'); });
最后,我们需要确保与服务器的连接设置正确。当我们在终端中启动服务器时,它将在浏览器中打开。
为此,请使用listen() 方法。
// Start the server app.listen(3000, () => { console.log('Server started on port 3000'); });
此方法将监听()来自服务器的请求。
完整的代码流程如下:
const express = require('express'); // Next initialize the application const app = express(); // routing path app.get('/', (req, res) => { res.send('Hello World!'); }); // Start the server app.listen(3000, () => { console.log('Server started on port 3000'); });
注意:上面的路由路径仅用于测试目的,以确认服务器正在工作和连接。我们将为我们正在创建的活动应用程序提供不同的文件。
在应用程序中安装 Express.js 后,您现在可以创建一个服务器来处理所有路由和连接。
要启动服务器,请转到您的终端。
使用关键字node,然后输入--watch,这是一个标志,用于在您进行更改时启动并自动重新启动服务器:
node --watch server.js
或者您可以出于相同目的安装nodemon。 nodemon 检测目录中的更改并重新启动您的应用程序。
npm install -g nodemon
然后使用以下命令运行您的服务器:
nodemon server.js
我们需要一个模板引擎来使用 Node.js 在浏览器中呈现 HTML 代码。在本教程中,我们将使用 ejs(嵌入式 JavaScript),但还有其他工具,例如 Pug(以前称为 Jade)和 Express Handlebar,它们也在服务器上呈现 HTML。
ejs 允许您在 HTML 中嵌入 JavaScript 来创建动态网页。
要安装 ejs,请运行:
npm install ejs
要在 server.js 中设置 ejs,需要并将 ejs 设置为模板引擎:
const express = require('express'); const app = express(); app.set('view engine', 'ejs');
通过此设置,您现在可以在 Node.js 应用程序中启用 HTML 代码的动态渲染。
要保存为应用程序创建的数据,您将使用 MongoDB。
MongoDB is a "Not Only SQL" (NoSQL) database that's designed for storing document collections. Traditional SQL databases organize data into tables, but MongoDB is optimised for handling large volumes of data.
To read more about this, check out this article.
Now we need to connect to the database which will be MongoDB for this tutorial.
Using MongoDB provides you with a Uniform Resource Locator (URL) to connect to your application. This URL connect you and acts as a communicator between the database and your application.
To get the URL, follow these simple steps:
Sign Up/Log In: Go to the MongoDB website and sign up for an account or log in if you already have one.
Create a Cluster: Once logged in, create a new cluster. This will set up your database.
Connect to Your Cluster: After your cluster is created, click the "Connect" button.
Choose a Connection Method: Select "Connect your application".
Copy the Connection String: MongoDB will provide a connection string (URL) like this:
mongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>?retryWrites=true&w=majority
6.Replace the Placeholders: Replace with your actual username, password, and database name.
Now that you have the URL, you can easily connect to your database.
To make this connection easier, we will use a tool called Mongoose.
Mongoose is a JavaScript library that makes it easier to work with MongoDB in a Node.js environment. It provides a simple way to model your data. You can also define schemas, do data validation, and build queries.
MongoDB has already provided you with a URL for connection. Now you'll use Mongoose to send your documents to the database.
To use Mongoose in your project, follow these steps:
Install Mongoose using npm.
npm i mongoose
In your server.js file, you need to require Mongoose to use it as a connector to the database.
const mongoose = require('mongoose');
After you require Mongoose, you need to define the connection URL provided in your server.js file.
server.js:
const mongoose = require('mongoose'); // Replace <username>, <password>, and <dbname> with your actual credentials const dbURL = 'mongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>?retryWrites=true&w=majority'; mongoose .connect(process.env.dbURL) .then((result) => { console.log('Connected to MongoDB'); app.listen(3000, () => { console.log('Server started on port 3000'); }); }) .catch((err) => { console.error('Could not connect to MongoDB:', err); });
This setup ensures that Mongoose acts as the connector. It connects your application to the MongoDB database.
Next, we need to create a model document called a Schema so that when you post data to your database it will be saved accordingly.
In the event.js file, you will use Mongoose to define the schema for the event documents. You'll specify the structure and data types for the documents you will send to your database.
Here's the event.js file created inside the model folder:
const mongoose = require('mongoose'); // Schema const EventSchema = new mongoose.Schema( { title: { type: String, required: true, }, date: { type: Date, required: true, }, organizer: { type: String, required: true, }, price: { type: String, required: true, }, time: { type: String, required: true, }, location: { type: String, required: true, }, description: { type: String, required: true, }, }, { timestamps: true } ); const Event = mongoose.model('event', EventSchema); module.exports = Event;
When this is done, export so you can use it in your server.js file by simply using the require keyword.
With the schema created, it can now be exported to the server.js file.
Your server.js will look like this:
const express = require('express'); const ejs = require('ejs'); const mongoose = require('mongoose'); const Event = require('../models/Events');// the event.js file
As we talked about earlier, we're using ejs in step 4 to render HTML code, allowing us to view the code in the browser.
Form Page
First, let's create a form page. With the form page created, you'll be able to make POST requests which will enable you to send data to your MongoDB database.
To create a basic form, ensure it includes:
An action attribute which specifies the route to send the data.
A method attribute which specifies the HTTP request method – in this case, the POST request.
A basic form:
<form action="/submit-event" method="POST"> <h2>Event Creation Form</h2> <label for="title">Title</label> <input type="text" id="title" name="title" required> <label for="date">Date</label> <input type="date" id="date" name="date" required> <label for="organizer">Organizer</label> <input type="text" id="organizer" name="organizer" required> <label for="price">Price</label> <input type="text" id="price" name="price" required> <label for="time">Time</label> <input type="text" id="time" name="time" required> <label for="location">Location</label> <input type="text" id="location" name="location" required> <label for="description">Description</label> <textarea id="description" name="description" rows="4" required></textarea> <button type="submit">Submit</button> </form>
NB: Make sure to add the name attribute to each input, or it won't post.
The form created above will let you post data to the specified route. You will then process and store it in your database.
Here's the result:
After creating the form page, we need to go back to the server.js file and create a POST request to handle the form submission.
server.js file:
// posting a data app.post('/submit-event', (req, res) => { const event = new Event(req.body); event.save() .then((result) => { res.redirect('/'); }) .catch((err) => { console.error(err); }); });
Now that the form can post data to the database, we can create the homepage to display the created events in the browser.
First, in your server.js file, you need to create a function. It will fetch all the events posted from the form and stored in the database.
Here’s how to set it up:
This is a function created at server.js to fetch all data from the database:
// To get all the event router.get('/', (req, res) => { Event.find() .then((result) => { res.render('index', { title: 'All event', events: result }) }) .catch((err) => { console.error(err); }) })
Next, we will dynamically loop through each part using a forEach loop in the homepage file. Since we are using ejs, the HTML file extension will be .ejs.
<div> <h2>All events</h2> <div> <% if (events.length > 0) { %> <% events.forEach(event => { %> <div> <h3><%= event.title %></h3> <p><%= event.description %></p> <a href="/event/<%= event.id %>"> Read More </a> </div> <% }) %> <% } else { %> <p>No events are available at the moment.</p> <% } %> </div> </div>
Remember that you installed ejs into your application to facilitate more dynamic components. It allows you to break your code down further to be more dynamic.
To further organize your code, you'll use something called Partials.
Partials let you break down your code into scalable, modular, and manageable parts, keeping your HTML organized.
First, let's create a partial for the navbar.
Inside your views folder, create a new folder named Partials
Inside the partials folder, create a new file called nav.ejs.
Cut out the navbar code from your homepage file and paste it into nav.ejs.
Example:
First, create the Partials folder and file:
Use the <%- include() %> syntax from ejs to include the nav.ejs partial across pages in your application where you want the navbar to appear.
Here's the code: <!DOCTYPE html> <html lang="en"> <%- include('./partial/head.ejs') %> <body> <%- include('./partial/nav.ejs') %> <main> hello </main> <%- include('./partial/footer.ejs') %> </body> </html>
With this setup, your HTML code will be organized. It will be easy to manage and update components like the navbar across different pages. You can use this approach on other parts of your application. For example, the head tag, footer tag, and other reusable components.
In this tutorial, we'll upload the project to GitHub. You'll protect your port number and MongoDB URL with secure storage. You'll also use an environment variable file, a configuration file known as .env. This file keeps sensitive information safe. It includes passwords and API URLs and prevents exposure.
Here's how to set it up using Node.js:
First, install the dotenv package.
npm i dotenv
Then create a .env file. Inside it, add your PORT number and MongoDB URL. It should look something like this:
PORT=3000 dbURl='mongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>?retryWrites=true&w=majority';
Then update your .gitignore file:
/node_modules .env
Adding .env to your .gitignore ensures that it is not included in your GitHub repository. This tells Git to ignore the .env file when uploading your code.
Then in your server.js file, require the dotenv package. Load the variables with this line at the top of the file:
To require it, simply type:
require('dotenv').config();
This way, you don't need to hardcode the PORT number and MongoDB URL in your server.js file. Instead, you can access them using process.env.PORT and process.env.dbURl.
So your server.js file will be cleaner and not messy ??
require('dotenv').config(); const express = require('express'); const ejs = require('ejs'); const mongoose = require('mongoose'); mongoose .connect(process.env.dbURL) .then((result) => { console.log('Connected to MongoDB'); app.listen(3000, () => { console.log('Server started on port 3000'); }); }) .catch((err) => { console.error('Could not connect to MongoDB:', err); });
To expand on this basic application, consider adding features such as:
User authentication
Event search and filter functionality
Event editing and deletion
Notifications for upcoming events
If you want to add some styling to your application, follow these steps:
First, create a public folder. Inside this folder, create a style.css file where you will write your custom CSS.
Then in your HTML file, link the style.css file in the
tag as you normally would:<link rel="stylesheet" href="/style.css">
To ensure your CSS file is served correctly, add the following line to your server.js file:
app.use(express.static('public'));
This application uses Tailwind CSS for styling. But using Tailwind is optional. You can use any CSS framework or write custom CSS to achieve your desired layout.
All images should be stored in the public folder and referenced in your HTML files. You should also ensure that the public folder is correctly set up in your server.js file to serve static files.
Here's an example of how to serve static files in server.js:
const express = require('express'); const app = express(); // Serve static files from the 'public' folder app.use(express.static('public'));
Congratulations! You've built a simple application using Node.js, Express.js, ejs, and MongoDB. With these fundamentals, you can expand and enhance your application to meet more specific needs and features.
Feel free to share your progress or ask questions if you encounter any issues.
如果您发现本文有帮助,请与其他可能也觉得有趣的人分享。
在 Twitter、LinkedIn 和 GitHub 上关注我,随时了解我的项目
感谢您的阅读?.
编码愉快!
以上是如何使用 Node.js 构建应用程序的详细内容。更多信息请关注PHP中文网其他相关文章!