Express란?
서버를 쉽게 만들수 있게 도와주는 라이브러리
npm init
npm install express
const express = require('express');
const app = express();
app.listen(8080, function() {
console.log('listening on 8080')
})
(server.js 파일)
app.get('/pet', function(req, res) {
res.send('펫용품 팔아요')
})
위의 문장을 server.js 에 추가하고
locallhost:8080/pet 으로 접속시 응답받은 문구가 띄워진다
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h4>안녕하세요 홈페이지입니다.</h4>
</body>
</html>
(server.js)
app.get('/', function(요청, 응답) {
응답.sendFile(__dirname +'/index.html')
});
이렇게 하면 index.html 파일을 server.js 랑 같은 경로에 있는
index.js 파일을 보내준다
sendFile() 함수 사용시 파일을 보낼 수 있다
__dirname 은 현재 파일의 경로를 뜻한다
app.get( 어쩌구, function( ){ } );
app.get('/write', ( ) => {어쩌구} ) ;
<form action="/add" method="POST">
<div class="form-group">
<label>오늘의 할일</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label>날짜</label>
<input type="text" class="form-control" name="date">
</div>
<button type="submit" class="btn btn-outline-secondary">Submit</button>
</form>
input 부분의 name 은 서버에서 어떤 input 에 적혀있던 데이터인지를 구분하기 위해서 적어준다
app.use(express.urlencoded({extended: true}))
body-parser 라이브러리를 설치하여 폼 데이터를 쉽게쉽게 처리가 가능하다
app.post('/add', function(req, res){
console.log(res.body);
req.send('전송완료')
});
server.js 를 위와같이 바꿔주면 누군가 /add 경로로 Post 요청을 할 때
터미널 콘솔창에 req.body 를 출력해볼 수 있다 .