Computer >> 컴퓨터 >  >> 프로그래밍 >> MongoDB

Node.js와 MongoDB로 만드는 회원가입 폼 완벽 가이드

이 글에서는 이름, 이메일, 비밀번호, 전화번호 등의 입력 항목을 포함한 간단한 사용자 회원가입 폼을 만들어 보겠습니다. 제출 버튼을 클릭하면 입력된 모든 사용자 정보가 MongoDB 데이터베이스에 저장되는 구조입니다.

사전 준비: 필수 패키지 설치

회원가입 폼을 만들기 전에 아래의 의존성 패키지들이 시스템에 정상적으로 설치되어 있어야 합니다.

  • Express: 미들웨어를 설정하여 HTTP 요청에 응답하는 역할을 담당하는 웹 프레임워크입니다. 다음 명령어로 설치할 수 있습니다.
npm install express --save
  • body-parser: HTTP POST 요청으로 전송된 데이터를 읽기 위해 필요한 Node.js 모듈입니다.
npm install body-parser --save
  • Mongoose: Node.js의 MongoDB 드라이버 위에서 동작하는 ODM(Object Data Modeling) 라이브러리입니다.
npm install mongoose --save

참고: 최신 버전의 Express(4.16 이상)에는 express.json()express.urlencoded()가 내장되어 있어 body-parser를 별도로 설치하지 않아도 됩니다. 하지만 기존 프로젝트와의 호환성을 위해 이 예제에서는 body-parser를 사용합니다.

예제 프로젝트 구성

  • 아래 파일들을 생성하고, 각 파일에 해당하는 코드를 붙여넣습니다.
    • app.js
    • public 폴더 생성 후 그 안에 아래 파일들을 넣습니다.
      • index.html
      • success.html
      • style.css
  • 다음 명령어로 애플리케이션을 실행합니다.
node app.js

전체 코드

app.js — 서버 및 데이터베이스 연결 로직

var express=require("express");
var bodyParser=require("body-parser");

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/tutorialsPoint');
var db=mongoose.connection;
db.on('error', console.log.bind(console, "connection error"));
db.once('open', function(callback){
    console.log("connection succeeded");
})
var app=express()

app.use(bodyParser.json());
app.use(express.static('public'));
app.use(bodyParser.urlencoded({
    extended: true
}));

app.post('/sign_up', function(req,res){
    var name = req.body.name;
    var email =req.body.email;
    var pass = req.body.password;
    var phone =req.body.phone;

    var data = {
        "name": name,
        "email":email,
        "password":pass,
        "phone":phone
    }
    db.collection('details').insertOne(data,function(err, collection){
    if (err) throw err;
        console.log("Record inserted Successfully");
    });
    return res.redirect('success.html');
})

app.get('/',function(req,res){
    res.set({
        'Access-control-Allow-Origin': '*'
    });
    return res.redirect('index.html');
}).listen(3000)

console.log("server listening at port 3000");

index.html — 회원가입 페이지

<!DOCTYPE html>
<html>
<head>
<title> Signup Form</title>
<link rel="stylesheet"
href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity=
"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<br>
<br>
<br>
<div class="container" >
<div class="row">
</div>
<div class="main">
    <form action="/sign_up" method="post">
    <h1>Welcome to Tutorials Point - SignUp</h1>
    <input class="box" type="text" name="name" id="name" placeholder="Name" required /><br>
    <input class="box" type="email" name="email" id="email" placeholder="E-Mail " required /><br>
    <input class="box" type="password" name="password" id="password" placeholder="Password " required/><br>
    <input class="box" type="text" name="phone" id="phone" placeholder="Phone Number " required/><br>
    <br>
    <input type="submit" id="submitDetails" name="submitDetails" class="registerbtn" value="Submit" />  <br>
    </form>
</div>
<div class="">
</div>
</div>
</div>
</body>
</html>

success.html — 가입 성공 페이지

<!DOCTYPE html>
<html>
<head>
<title> Signup Form</title>
<link rel="stylesheet"
href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity=
"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<br>
<br>
<br>
<div class="container" >
    <div class="row">
    <div class="col-md-3">
</div>
<div class="col-md-6 main">
    <h1> Signup Successful</h1>
</div>
<div class="col-md-3">
</div>
</div>
</div>
</body>
</html>

style.css — 스타일시트

.main{
    padding:20px;
    font-family: 'Helvetica', serif;
    box-shadow: 5px 5px 7px 5px #888888;
}
.main h1{
    font-size: 40px;
    text-align:center;
    font-family: 'Helvetica', serif;
}
input{
    font-family: 'Helvetica', serif;
    width: 100%;
    font-size: 20px;
    padding: 12px 20px;
    margin: 8px 0;
    border: none;
    border-bottom: 2px solid #4CAF50;
}
input[type=submit] {
    font-family: 'Helvetica', serif;
    width: 100%;
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 16px 32px;
    margin: 4px 2px;
    border-radius: 10px;
}
.registerbtn {
    background-color: #4CAF50;
    color: white;
    padding: 16px 20px;
    margin: 8px 0;
    border: none;
    cursor: pointer;
    width: 100%;
    opacity: 0.9;
}

실행 결과 확인

서버를 실행한 뒤 웹 브라우저에서 아래 주소 중 하나에 접속하면 회원가입 페이지를 확인할 수 있습니다.

https://127.0.0.1:3000/index.html 또는 https://localhost:3000/index.html

C:\Users\tutorialsPoint\> node app.js
server listening at port 3000
(node:73542) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:73542) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
connection succeeded

참고: 콘솔에 표시되는 DeprecationWarning은 구버전 MongoDB 드라이버 관련 경고일 뿐이며, 애플리케이션 동작에는 문제가 없습니다. 최신 드라이버를 사용하면 해당 경고가 사라집니다.

회원가입 페이지 화면

Node.js와 MongoDB로 만드는 회원가입 폼 완벽 가이드

가입 성공 페이지 화면

Node.js와 MongoDB로 만드는 회원가입 폼 완벽 가이드

MongoDB에 레코드가 성공적으로 저장된 모습

Node.js와 MongoDB로 만드는 회원가입 폼 완벽 가이드

마무리

이처럼 Express와 Mongoose만으로도 HTML 폼 데이터를 받아 MongoDB에 저장하는 기본적인 회원가입 시스템을 손쉽게 구축할 수 있습니다. 실제 서비스에서는 비밀번호 해싱(bcrypt), 입력값 유효성 검증, 중복 이메일 체크 등의 추가 처리를 함께 적용하는 것이 좋습니다.