티스토리 뷰

이전에 IntelliJ에서 Node.js 프로젝트를 생성해보았는데, 이 페이지에서는 Terminal을 통해 생성하는 방법과 폴더 구조에 대해 알아본다.

참고) http://kkumalog.tistory.com/48


# Terminal을 통한 Node.js 프로젝트 생성

원하는 디렉토리에 폴더를 생성한다. (ex-TestProject)

$ cd TestProject/
$npm init

이 명령을 실행하면 애플리케이션의 이름 및 버전과 같은 몇 가지 정보에 대해 프롬프트한다. 대부분의 항목에서 ENTER 키를 눌러 기본값을 수락할 수 있다.

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (testproject) 
version: (1.0.0) 
description: 
entry point: (index.js) 
test command: 
git repository: 
keywords: 
author: 
license: (ISC) 
About to write to /Users/kkuma/TestProject/package.json:

{
“name”: “testproject,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1”
},
“author”: “”,
“license”: “ISC”
}

Is this OK? (yes) 


$ pwd

pwd (print working directory, 현재 작업 중인 디렉터리의 이름을 출력)


$ npm install express —save

express를 임시로 설치하고 종속 항목 목록에 추가하지 않으려면, —save 옵션 생략  npm install express


$ npm install body-parser


# app.js 파일 생성

 - 이전 포스트로 이미 시작을 했다면, app.js는 이미 존재할 것이다. 아래의 package를 설치한 후 다음단계부터 진행하면된다.


 # api, router 폴더 생성

구조는 app.js  router  api 순으로 호출을 하여 사용할 것이다.


# Code

이 페이지는 Node.js로 프로젝트를 생성하고, router를 이용하는 방법을 설명하고있다.

(추후에 로그인페이지를 구현하고자해서 파일의 이름은 login.js를 사용한다.)

1) app.js

const express = require(‘express’);
const login = require(‘./router/login’);
const app =  express();

app.get(‘/‘, function(req, res) {
res.send(‘Hello World!’);
});
app.use(‘/login’, login);

app.listen(3001, *function*() {
console.log(‘Example app listening on port 3001’);
});


2) router/login.js

const router = require(‘express’).Router();

const login = require(‘../api/login’);


router.get(‘/‘, login);


module.exports = router;


3)  api/login.js

const login = function getLogin(req, res, next) {
res.send(‘Login Page’);
}
module.exports = login;


함수의 파라미터 순서는 req, res, next 이다. 파라미터의 순서가 바뀌면 에러가 생겨 진행할 수 없을 수도 있다.

만약 정의된 함수가 여러개라면 module.exports = { login, logout, signup} 형태로 사용할 수 있는데, 이 경우에는 라우터에서도 객체 형태로 받게된다.

ex) const api = require(‘../api/login’);
router.get(‘/‘, api.login);


# 서버실행

app.js를 실행한다 (Run ‘app.js’ 또는 Debug ‘app.js’)

https://localhost:3001

https://localhost:3001/login


댓글
최근에 올라온 글
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Total
Today
Yesterday