본문 바로가기

전체 글58

[nodeJS] 자주 사용하는 Node.js 패턴 정리 1 (모듈 패턴) 1. 모듈 패턴 (Module Pattern) 애플리케이션의 기능을 독립적인 코드 블록으로 나누어 작성하는 방식 각 블록은 재사용 가능하며 다른 모듈들과 결합하여 하나의 애플리케이션을 구성 2. Node.js에서의 모듈 패턴 Node.js는 CommonJS 표준을 따르는 모듈 시스템을 내장 이에 따라 작성한 코드를 모듈화하여 다른 파일에서 재사용하거나 의존 관계를 관리 3. 기본 모듈 패턴 기본 모듈 패턴은 파일 단위로 코드를 모듈화하여 작성하고, exports 객체를 사용하여 외부에서 접근 가능한 코드를 정의 // math.js const add = (a, b) => a + b; const subtract = (a, b) => a - b; const multiply = (a, b) => a * b; c.. 2023. 6. 21.
[nodeJS] Node.js와 Express에서 미들웨어 (Middleware) 사용하기 1. 미들웨어 (Middleware) 요청과 응답 사이에서 수행할 연산이나 작업을 처리하는 함수 사용자가 요청한 작업을 처리한 후 다음 미들웨어로 결과를 전달하거나 응답을 반환\ Express에서는 미들웨어를 사용하여 애플리케이션의 로직을 명확하게 구조화하고 모듈화 가능 2. 미들웨어 사용법 요청 객체(req), 응답 객체(res), 다음 미들웨어를 실행할 함수(next) 총 3개의 인수 받음 요청과 응답 객체를 사용하여 필요한 로직을 처리한 후에 next() 함수로 다음 미들웨어로 이동 function myMiddleware(req, res, next) { // 미들웨어 로직 console.log("Hello from my middleware!"); // 다음 미들웨어로 넘어감 next(); } 3. .. 2023. 6. 20.
[nodeJS] 변수 선언하기 (var, let, const) JavaScript (nodeJS)에서 변수를 선언하는 방법 : var, let, const 1. var ES6 이전의 JavaScript에서 변수를 선언하는 방법 선언한 변수를 함수 스코프 전체에서 사용 가능하기 때문에 사용하지 않는 것이 좋음 (변수의 스코프가 불분명하고 뜻밖의 상황에서 변경 가능) var name = "wrtn"; console.log(name); // wrtn if (true) { var name = "JS"; console.log(name); // JS } console.log(name); // JS name'을 선언하고 값을 할당한 후, if 블록 안에서 동일한 이름의 변수를 선언하고 다른 값을 할당할 경우 바깥쪽에서 'name'을 다시 가져올 때 변수의 값이 변경됨. 2. l.. 2023. 6. 19.
[nodeJS] body-parser로 JSON 파싱하기 1. body-parser HTTP 요청의 본문(body)을 쉽게 파싱하도록 도와주는 미들웨어 req.body는 body-parser를 사용하기 전에는 디폴트 값으로 Undefined이 설정되서 그냥 사용 시 에러 발생 요청 데이터를 서버에서 처리하기 쉽도록 데이터 포맷 지원 JSON (application/json) URL-encoded (application/x-www-form-urlencoded) Raw (application/octet-stream) Text (text/plain) 2. 사용 방법 npm install body-parser const express = require('express'); const bodyParser = require('body-parser'); const app .. 2023. 6. 17.
[nodeJS] Axios로 HTTP 요청하기 1. Axios HTTP 요청과 응답을 쉽게 만들고 처리할 수 있는 라이브러리 npm install axios 2. GET 요청 axios.get() 사용 const axios = require('axios'); // GET 요청 const getUser = async () => { try { const url = 'get 요청을 해야하는 url' const response = await axios.get(url); // 응답 데이터 출력 console.log(response.data); } catch (error) { console.error(error); } }; // 함수 호출 getUser(); 3. POST 요청 axios.post() 사용 const axios = require('axios').. 2023. 6. 16.
[nodeJS] Multer로 파일 업로드 구현하기 1. Multer nodeJS 서버에 파일을 업로드 할 때 사용하는 라이브러리 npm install multer 2. 간단한 파일업로드 HTML 폼 만들기 Upload a file Upload 3. app.js에 파일 업로드 설정하기 업로드 파일은 'uploads/' 폴더에 저장하고 파일 업로드가 성공적으로 완료되면, 클라이언트에게 업로드 성공 응답하기 // 필요한 모듈을 불러옵니다. const express = require('express'); const multer = require('multer'); const app = express(); const port = 3000; // Multer 설정: 업로드된 파일을 'uploads/' 폴더에 저장 const upload = multer({ dest.. 2023. 6. 15.
[nodeJS] Moment로 날짜, 시간 포맷 바꾸기 1. Moment JavaScript에서 날짜와 시간을 다루기 위한 라이브러리 다음주 목요일, 1달 전과 같은 상대 시간 표시 가능 npm i moment 2. 날짜와 시간 문자열 포맷 변경하기 const moment = require('moment'); const date = moment('2023-06-14T09:30:21Z'); console.log(date.format('YYYY-MM-DD HH:mm:ss')); // '2023-06-14 09:30:21' 3. 날짜 더하기, 빼기 const moment = require('moment'); const today = moment(); const tomorrow = today.clone().add(1, 'days'); console.log(tomor.. 2023. 6. 14.
[nodeJS] Node.js 개발에 흔히 사용되는 라이브러리 5개 1. Express Node.js를 위한 가벼운 웹 애플리케이션 프레임워크, 빠르게 API 개발이 가능 const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => res.send('Hello World!')); app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`)); 2. Axios Promise 기반의 HTTP 요청 라이브러리 const axios = require('axios'); axios.get('https://api.example.com/data') .then(res.. 2023. 6. 13.
[nodeJS] nodemailer로 메일 보내기 1. nodemailer란? SMTP/SMTPS/STARTTLS 전송 프로토콜을 사용하여 이메일을 보낼 수 있는 라이브러리 2. nodemailer사용하기 nodemailer모듈 설치 npm install nodemailer 3. Gmail 계정으로 이메일을 보내기 nodemailer 라이브러리의 createTransport() 함수를 사용하여 Gmail SMTP 서버와 연결을 설정 sendMail() 함수를 사용하여 실제 이메일을 전송 const nodemailer = require('nodemailer'); // SMTP 전송 서버 설정 const transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: 'your_gmail.. 2023. 6. 12.