[Node.js]초기세팅

Jimin_Note·2022년 8월 29일
1

🐛node.js

목록 보기
2/5
post-thumbnail

🌟Node.js 초기세팅하기

📌node 설치 확인

> node -v
#v16.15.0

📌npm 초기화

-> package.json 추가하기

> npm init #내용을 직접 쓰라고함
> npm init -y #폴더명을 기준으로 자동생성
Wrote to /Users/jimny/project/node_test/package.json:

{
  "name": "node_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js", -> app.js 로 수정                                                                                       
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

📌express 설치

-> node_modules 폴더와 package-lock.json 생성

npm install express

📌모듈 설치

✅ morgan

  • node.js용 HTTP 요청 로거 미들웨어

✅ cookie-parser

  • cookie 헤더 파싱(구문 분석), 쿠키 이름에 의해 키가 지정된 객체로 req.cookies를 채움
  • secret 문자열을 전달하여 선택적으로 서명된 쿠키 지원 활성화
  • secret 문자열은 다른 미들웨어에서 사용할 수 있도록 req.secret 할당

✅ express-session

  • express 프레임워크에서 세션을 관리하기 위해 필요한 미들웨어
npm install morgan cookie-parser express-session dotenv

📌nodemon 설치

nodemon : 소스코드가 바뀔 때 마다 자동으로 노드를 재실행해주는 패키지

npm install nodemon

📌package.json 수정

{
  "name": "node_test",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",                                                                                    
  "scripts": {
    "start" : "nodemon app", #개발용으로만 사용하고 배포후 에응 서버 코드가 빈번하게 변경될 일이 없으므로 nodemon 쓰지 않아도된다!
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

📌app.js작성

const express = require('express');
const morgan = require('morgan');
const cookiParser = require('cookie-parser');
const session = require('express-session');
const dotenv = require('dotenv');
//설치한 미들웨어 및 모듈  불러오기

dotenv.config();
const app = express();
app.set('port',process.env.PORT || 3000);
//app.set('port,포트) : 서버가 실행될 포트 설정

app.use(morgan('dev'));
app.use('/',express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.use(express.urlencoded({ extended: false}));
app.use(cookiParser(process.env.COOKIE_SECRET));
app.use(session({
    resave: false,
    saveUninitialized: false,
    secret: process.env.COOKIE_SECRET,
    cookie: {
        httpOnly: true,
        secure: false,
    },
    name: 'session-cookie',
}));

app.use((req, res, next) => {
    console.log('모든 요청에 다 실행됩니다.');
});

app.get('/',(req,res)=>{
    res.send('Hello, Express');
});
/*app.get(주소, 라우터) : 주소에 대한 GET요청이 올 때 어떤 동작을 할지 적는 부분
ex) app.post, app.patch, app.put, app.delete, app.options
express에서는 http와 다르게 res.write, rew.end 대신 res.send 사용
**/

app.listen(app.get('port'),()=>{
    console.log(app.get('port'),'번 포트에서 대기 중');
});

📌 .env 작성

COOKIE_SECRET=cookiesecret

profile
Hello. I'm jimin:)

0개의 댓글