Node.js로 애플리케이션을 구축하는 방법

WBOY
풀어 주다: 2024-08-09 18:44:36
원래의
1111명이 탐색했습니다.

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용 웹 애플리케이션 프레임워크이자 우리 애플리케이션에서 사용하는 타사 라이브러리입니다.

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!');
});
로그인 후 복사

마지막으로 서버 연결이 올바르게 설정되었는지 확인해야 합니다. 터미널에서 서버를 시작하면 브라우저에서 열립니다.

이를 위해서는 listening() 메소드를 사용하세요.

// 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(Embedded JavaScript)를 사용하지만 서버에서 HTML을 렌더링하는 Pug(이전의 Jade) 및 Express Handlebar와 같은 다른 것도 있습니다.

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으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!