이번 강의에서 진행할 내용은 크게 아래와 같다.

1. 클라이언트로부터 POST로 요청받은 데이터를 parsing 하기 위한 body-parser 설치

2. /campground에 새로운 name와 imageUrl을 추가하기 위한 페이지 생성

3. 전달받은 name과 imageUrl를 newCampground object로 저장한 후 campground 배열에 저장(push)

4. /campground에 전달받은 name과 imageUrl을 출력

 

 

1. body-parser 설치 및 호출

1-1. body-parser란? POST method로 파라미터가 서버로 전송되었을 경우, 해당 파라미터를 추출하기 위한 패키지

[그림1] 서버에 body-parser 설치

1-2. app.js에서 bodyParser 호출

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));

body-parser에 대한 설명은 github 링크 참조

 

 

1-3. 새로운 route 추가 및 post 동작 테스트

app.post("/campgrounds", (req, res) => {    //express 서버에서 '/campgrounds'에 'POST'가 요청될 경우 
	res.send("YOU HIT THE POST ROUTE");		// "YOU HIT.." 라는 데이터를 클라이언트로 response한다.
});

app.get("/campgrounds/new" (req, res) => { //	'/campegrounds/new'로 GET이 요청될 경우 
	res.render("new")					   //   YelpCamp/v1/view 아래에서 new라는 이름의 파일을 찾아 렌더링하여 응답한다. 
});

 

 

[그림 2]Postman으로 GET method Request

 

 

 

[그림 3] Postman으로 POST method Request

 

 

2. 데이터를 전달받을 ejs 생성

<%- include("partials/header")%>		<!--lesson 296 참조-->

<h1>Create a New Campground</h1>
  <form action="/campgrounds" method="POST">			<!--아래의 input 값을 POST method로 /campgrounds에게 request-->
    <input type="text" name="name" placeholder="Insert name">		<!--입력될 데이터는 name이란 이름 속성을 가지고 있음-->
    <input type="text" name="image" placeholder="Insert imageUrl">  <!--입력될 데이터는 image이란 이름 속성을 가지고 있음--> 
    <button>Submit!</button>							<!--해당 버튼을 누르면 데이터가 전송됨-->
  </form>
<a href="/campgrounds">Go back</a>
<%- include("partials/footer"%>		<!--lesson 296 참조-->

[그림 4] new.ejs 페이지(/campgrounds/new 라는 주소를 가지고 있음 "1-3" 참조)

 

 

3. POST로 전달된 파라미터를 저장하여 /campgrounds에서 출력

3-1. /campgrounds/new로 받을 데이터를 저장하기 위한 array 설정

기존에 사용하고 있는 지역변수인 campgrounds를 전역변수로 재설정하여 /campgrounds/new 에서 해당 array에 접근할 수 있도록 한다. 만약 campgrounds array가 지역변수로 되어 있을 경우 다른 메소드에서 해당 값에 접근이 불가능하다.

[그림 5] 단순히 app.get("/campgrounds", (req, res)...... 메소드 내부에 있는 데이터를 밖으로 빼주면 된다.

 

3-2. /campgrounds로 들어온 POST 요청에 들어있는 name과 image 저장 

app.post("/campgrounds/new", (req, res) => {  // /campgrounds/new라는 주소를 post로 요청받으면 아래 로직 수행
	const name = req.body.name		// 서버로 요청된 body태그 내의 name이란 name을 가진 데이터를 const name에 저장
    const image = req.body.image 	// 서버로 요청된 body태그 내의 image란 name을 가진 데이터를 const image에 저장
    const newCampground = {name: name, image: image} // 위의 전달 받은 데이터를 newCampground object에 저장 
    campgrounds.push(newCampground) // 전역변수 campground array에 newCampground object를 push(입력) 한다.
    res.redirect("/campgrounds")    // 마지막으로 응답 시 /campgrounds로 페이지를 리다이렉트 시킨다. 
});
    

최종적으로 저장된 값은 그림 5의 const campgrounds에 저장된다. 

 

 

3-3. campgrounds.ejs에 새로운 name과 image를 추가할 수 있는 페이지로 이동하는 링크 추가

<%- include("partials/header%>

<h1> This is the campgrounds page! </h1>
<a href="/campgrounds/new">Add New Campground</a>		<!--/campgrounds/new로 이동하는 링크 추가-->

<% campgrounds.forEach((campground) => {%>
  <div>
        <h4>
            <%= campground.name %>
            <img src="<%= campground.image %>">
        </h4>
  </div>
<%});%>

<%- include("partials/footer") %>

 

 

4. 실제 서버 동작여부 테스트

4-1. /campgrounds로 접속

[그림 6] Add new Campground 링크 클릭

 

4-2. /campgrounds/new 페이지에서 실제 데이터 입력 및 submit 버튼 클릭

[그림 7] 필드에 데이터 입력

 

 

[그림 8] Reqest Method: POST 로 [그림 7]에서 입력한 데이터를 클라이언트에서 서버로 전달.  

 

 

[그림 9] 실제로 express 서버에 해당 데이터가 전달됨. 

 

+ Recent posts