首頁 > web前端 > js教程 > 如何使用 Node.js 建立應用程式

如何使用 Node.js 建立應用程式

WBOY
發布: 2024-08-09 18:44:36
原創
1162 人瀏覽過

Node.js 它是一個運行時環境,允許您在伺服器端運行 JavaScript 程式碼以建立伺服器端應用程式。它非常適合創建快速且可擴展的應用程式。

在本文中,我將以一個簡單的事件管理應用程式為例,向您展示如何使用 Node.js、Express.js 和 MongoDB 建立應用程式。

最後,您將了解如何設定 Node.js 專案、使用 Express.js 建立伺服器、顯示具有嵌入式 JavaScript 的動態頁面,以及連接到 MongoDB 資料庫來處理資料。

你將學到什麼

  • 設定 Node.js 專案
  • 使用 Express.js 建立伺服器
  • 使用ejs渲染動態頁面
  • 連接到 MongoDB 資料庫
  • 為您的資料建立模型和模式
  • 處理 HTTP 請求和回應

How to Build an Application With Node.js

先決條件

  • Node.js 安裝在您的系統上。
  • 對 MongoDB 有很好的了解。
  • 您喜歡的程式碼編輯器,例如 Visual Studio Code 或 Sublime Text。

第 1 步:設定您的開發環境

安裝 Node.js 和 npm

首先,您需要下載並安裝 Node.js。然後您可以透過執行以下命令來驗證安裝:node -v 和 npm -v。

初始化一個新項目

為您的專案建立一個新目錄。然後在終端機中使用 npm 初始化項目: npm init -y。

mkdir event-app
cd event-app
npm init -y
登入後複製

運行 npm init -y 建立 package.json 文件,如上所示。這個文件至關重要。它儲存並追蹤您的應用程式所需的所有第三方程式庫(依賴項)。

第 2 步:設定伺服器

要設定伺服器,請建立一個名為 server.js 或 app.js 的檔案。這些都是常見的名字。它們因其描述性而被使用。但是,您可以根據自己的喜好命名該檔案。

server.js 檔案將用於建立一個伺服器,該伺服器將用於管理、控制和路由到我們應用程式中的必要頁面。

第 3 步:安裝並設定 Express.js

Express.js 是 Node.js 的流行 Web 應用程式框架,也是我們在應用程式中使用的第三方函式庫。

Express 簡化了 HTTP 請求的各種路由的處理和定義。它使您能夠管理應用程式的路由並將其連接到伺服器。

使用 Express:

透過在終端機中執行以下命令來安裝 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
登入後複製

第 4 步:建立動態模板

我們需要一個模板引擎來使用 Node.js 在瀏覽器中呈現 HTML 程式碼。在本教程中,我們將使用 ejs(嵌入式 JavaScript),但還有其他工具,例如 Pug(以前稱為 Jade)和 Express Handlebar,它們也在伺服器上呈現 HTML。

ejs 允許您在 HTML 中嵌入 JavaScript 來建立動態網頁。

要安裝 ejs,請執行:

npm install ejs
登入後複製

要在 server.js 中設定 ejs,需要並將 ejs 設定為範本引擎:

How to Build an Application With Node.js

const express = require('express');
const app = express();
app.set('view engine', 'ejs');
登入後複製

透過此設置,您現在可以在 Node.js 應用程式中啟用 HTML 程式碼的動態渲染。

第 5 步:將資料儲存到 MongoDB

要儲存為應用程式建立的數據,您將使用 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.

Step 6: Connect to the Database

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.

How to get the URL

To get the URL, follow these simple steps:

  1. Sign Up/Log In: Go to the MongoDB website and sign up for an account or log in if you already have one.

  2. Create a Cluster: Once logged in, create a new cluster. This will set up your database.

  3. Connect to Your Cluster: After your cluster is created, click the "Connect" button.

  4. Choose a Connection Method: Select "Connect your application".

  5. 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.

What is 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.

How to make a connection

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.

Step 7: Create the Model for the Document Structure

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.

To create this model:

  • Create a folder named models to keep your application organized.
  • Inside the model's folder, create a file called event.js.

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
登入後複製

Step 8: Create HTML Pages

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:

How to Build an Application With Node.js

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);
    });
});
登入後複製

The Homepage

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>
登入後複製

Step 9: Create Partials

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.

How to Create a Partial:

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:

How to Build an Application With Node.js

Use the <%- include() %> syntax from ejs to include the nav.ejs partial across pages in your application where you want the navbar to appear.

How to Build an Application With Node.js

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.

Step 10: Create an Environment Variable File (.Env)

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);
  });
登入後複製

Further Steps

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

How to Style the Application

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.

How to Include Images

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'));
登入後複製

Conclusion

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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板