진행 환경 : VSCode
빈 폴더 생성
mkdir test
생성한 폴더로 이동
cd test
vscode 터미널 창에 npm init
입력
위의 사진처럼
Press ^C at any time to quit.
package name: (nodeclustertest) ...
라는 문구가 뜨면 엔터로 스킵(원하는 값 입력 가능)
이후 Is this OK? (yes)
가 뜨고 yes 입력시 package.json 생성됨
mysql2, express, cors, nodemon 설치
npm install mysql express cors --save && npm install -D nodemon
nodemon : 노드가 실행하는 파일이 속한 디렉터리를 감시하고 있다가 파일이 수정되면 자동으로 노드 애플리케이션을 재시작하는 확장 모듈
npm install -D ~
는 --production 옵션을 추가하여 배포시 반영되지 않음
...
"scripts": {
"start" : "node index.js",
"dev" : "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
scripts에 start와 dev를 지정해주어 npm start
/ npm dev
시 node가 실행되도록 한다.
const createError = require('http-errors');
const express = require("express");
const cors = require("cors");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// localhost:8080/ 으로 get요청 받으면 hello world 출력
app.get('/', (req,res) => {
res.send('hello world');
})
//catch 404 error
app.use(function(req, res, next) {
next(createError(404));
});
const port = 8080;
app.listen(port, () => {
console.log("app start on port 8080");
})
module.exports = app;
이제 터미널창에 npm start
라고 치면 동작한다.