-> http 요청과 응답을 좀 더 편하게 사용할 수 있도록 도와주는 모듈, 자유도가 높고 라우팅, 미들웨어 등 개발자가 원하는 방식으로 구성할 수 있다. 보일러 플레이팅 가능
npm init -y
npm i express
const express = require("express");
//서버 인스턴스 생성
const app = express();
// 기존에는 아래처럼 했다면
http.createServer((req,res)=>{
const URL = req.url;
switch(URL) {
case "/"
res.end("hello nodejs");
}
// })
// 이제는 express를 사용하기 때문에 아래처럼 하면된다.
app.get("/",(req,res)=>{
res.send("hello nodejs");
});
app.listen(5000,()=>{
console.log("서버 잘 열림");
});
그리고 터미널에서 node index.js 를 입력해서 실행하지않고
package.json의 script 명령어에서 설정할 수 있다.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js",
"dev": "node index.js"
}
start는 npm start로 실행가능한데, dev처럼 임의로 정한 것은 npm run dev로 해야 실행가능하다.
-> 경로에 대한 조작을 도와주는 모듈, 파일시스템의 상대경로나 절대경로를 쉽게 설정할 수 있도록 하는 메서드를 지원한다.
const express = require("express");
const path = require("path");
const app = express();
app.get("/",(req,res)=>{
const body = path.join(__dirname, "views", "index.html");
console.log(body);
// 출력결과 : C:\Users\이재영\Desktop\20230310-master\20230502\views\index.html
console.log(__dirname);
// 출력결과 : C:\Users\이재영\Desktop\20230310-master\20230502
// sendFile 메서드는 html 파일을 브라우저로 보내준다.
res.sendFile(body);
});
app.listen(5000,()=>{
console.log("서버 잘 열림");
});
-> ejs 는 Embedded JavaScript 로 자바스크립트를 포함한 html 이라고 생각하면 된다. 템플릿 엔진은 서버사이드 렌더링으로 클라이언트가 요청하면 서버측에서 html을 만들어서 브라우저에 보여준다.
body-parser는 express의 미들웨어로,
요청으로 받은 body의 내용을 req요청 객체 안에 있는 body 객체로 담아준다.
req.body로 호출이 가능해진다.
미들웨어란, 요청과 응답을 하는 사이 중간에 동작하는 함수이다.
외부 모듈 설치 한번에 하는 방법
->npm i ejs mysql2
const express = require("exprees");
const mysql2 = require("mysql2");
const path = require("path");
const bodyParser = require("body-parser");
const app = express();
// express에는 set, use 메서드가 있는데
// set 메서드 : express의 view 등등 설정할 수가 있다. 파일이 있는 폴더의 경로 설정을 할수 있다.
// use 메서드 : 요청 또는 응답시 실행되는 미들웨어를 추가할 수 있다.
// views 속성으로 사용할 파일들의 경로 지정
app.set("views",path.join(__dirname,"views2"));
// view 엔진으로 ejs로 사용하겠다고 설정.
app.set("view engine", "ejs");
// true : 쿼리 스트링 모듈의 기능이 좀 더 확장된 qs 모듈을 사용하여 다른 방식의 인코딩 할때
// false : express 기본 내장된 쿼리 스트링 모듈을 사용해 기본 방식의 인코딩 할때(권장)
// express 버전이 올라가면서 bodyParser를 지원해줘서 아래처럼 사용할 수 있음.
app.use(express.urlencoded({extended:false}));
const _mysql = mysql2.createConnection({
user : "root",
password : "admin",
database : "test8"
});
_mysql.query("select * from products",(err,res)=>{
if(err){
const sql = "CREATE TABLE products(id INT AUTO_INCREMENT PRIMARY KEY, name varchar(20), number varchar(20), series varchar(20))"
_mysql.query(sql);
}
else{
console.log(res);
}
});
app.get("/",(req,res)=>{ //루트 url 요청시 처리
_mysql.query("select * from products",(err,result)=>{
//
res.render("main2",{data:result});
});
});
app.post("/insert",(req,res)=>{
// req 요청의 내용이 들어있다.
const data =req.body;
// body 객체 안에 form에서 요청으로 보낸 데이터가 객체로 들어있다.
// 객체 안에 있는 키값들은 input들의 name으로 정해준 키로 값이 들어있다.
const sql = "INSERT INTO products (name,number,series)VALUES(?,?,?)";
// query 메서드 두번째 매개변수로 배열의 형태로 value를 전달해 줄수 있다.
_mysql.query(sql,[data.name, data.number, data.series],()=>{
//redirect 메서드 : 매개변수로 전달한 URL로 페이지를 전환 시킨다.
//경로로 이동 시킨다.
res.redirect("/");
});
});
// 삭제를 해보자
app.get("/delete/:id",(req,res)=>{
// :id url 요청에서 파라미터 값이라고 한다.
// 1이라는 값을 가져올수가 있다.
// 예) http://localhost:3000/delete/1
// {id:1}이렇게 요청의 객체에 들어있다.
// req.params.id === 1
const sql = "delete from products where id=?";
_mysql.query(sql,[req.params.id],()=>{
res.redirect("/");
})
});
app.listen(5000,()=>{
console.log("서버 잘 열렸음");
});
insert.ejs
<form action="/insert" method="post">
<label for="">이름</label>
<input type="text" name="name">
<label for="">전화번호</label>
<input type="text" name="number">
<label for="">시리즈</label>
<input type="text" name="series">
<button type="submit">추가</button>
</form>
main2.ejs
<table style="width: 100%;">
<a href="/insert">추가 페이지</a>
<tr>
<th>삭제</th>
<th>수정</th>
<th>아이디</th>
<th>이름</th>
<th>전화번호</th>
<th>시리즈</th>
</tr>
<!-- 페이지에 리스트면 여러개의 데이터가 있을텐데 -->
<!-- html 동적으로 뭔가를 해본적이 없다. -->
<% data.forEach(function (el, index){ %>
<tr>
<td>삭제</td>
<td>수정</td>
<td><%= el.id %></td>
<td><%= el.name %></td>
<td><%= el.number %></td>
<td><%= el.series %></td>
</tr>
<% }); %>
</table>