Node.js로 애플리케이션을 구축하는 방법
Node.js는 서버 측 애플리케이션을 구축하기 위해 서버 측에서 JavaScript 코드를 실행할 수 있는 런타임 환경입니다. 빠르고 확장 가능한 애플리케이션을 만드는 데 적합합니다.
이 기사에서는 간단한 이벤트 관리 앱을 예로 들어 Node.js, Express.js 및 MongoDB를 사용하여 애플리케이션을 구축하는 방법을 보여 드리겠습니다.
마지막에는 Node.js 프로젝트 설정 방법, Express.js로 서버 생성 방법, 내장된 JavaScript가 포함된 동적 페이지 표시 방법, MongoDB 데이터베이스에 연결하여 데이터 처리 방법을 배우게 됩니다.
당신이 배울 내용
- Node.js 프로젝트 설정
- Express.js로 서버 만들기
- ejs를 사용하여 동적 페이지 렌더링
- MongoDB 데이터베이스에 연결
- 데이터에 대한 모델 및 스키마 생성
- HTTP 요청 및 응답 처리
전제 조건
- 시스템에 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를 템플릿 엔진으로 요구하고 설정하세요.
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:
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.
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:
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:
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.
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

각각의 엔진의 구현 원리 및 최적화 전략이 다르기 때문에 JavaScript 엔진은 JavaScript 코드를 구문 분석하고 실행할 때 다른 영향을 미칩니다. 1. 어휘 분석 : 소스 코드를 어휘 단위로 변환합니다. 2. 문법 분석 : 추상 구문 트리를 생성합니다. 3. 최적화 및 컴파일 : JIT 컴파일러를 통해 기계 코드를 생성합니다. 4. 실행 : 기계 코드를 실행하십시오. V8 엔진은 즉각적인 컴파일 및 숨겨진 클래스를 통해 최적화하여 Spidermonkey는 유형 추론 시스템을 사용하여 동일한 코드에서 성능이 다른 성능을 제공합니다.

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

C/C에서 JavaScript로 전환하려면 동적 타이핑, 쓰레기 수집 및 비동기 프로그래밍으로 적응해야합니다. 1) C/C는 수동 메모리 관리가 필요한 정적으로 입력 한 언어이며 JavaScript는 동적으로 입력하고 쓰레기 수집이 자동으로 처리됩니다. 2) C/C를 기계 코드로 컴파일 해야하는 반면 JavaScript는 해석 된 언어입니다. 3) JavaScript는 폐쇄, 프로토 타입 체인 및 약속과 같은 개념을 소개하여 유연성과 비동기 프로그래밍 기능을 향상시킵니다.

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

실제 세계에서 JavaScript의 응용 프로그램에는 프론트 엔드 및 백엔드 개발이 포함됩니다. 1) DOM 운영 및 이벤트 처리와 관련된 TODO 목록 응용 프로그램을 구축하여 프론트 엔드 애플리케이션을 표시합니다. 2) Node.js를 통해 RESTFULAPI를 구축하고 Express를 통해 백엔드 응용 프로그램을 시연하십시오.

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.
