라우트 

 

비슷한 기능을 하는 app.get() 함수 2개를 중복만 제거하고 하나로 합쳐보자. 

 

 

여러 경로를 한번에 처리 

 

get() 함수에서 파일명, 파일 내용을 가져오는 코드의 중복을 제거. 

 

새 글 쓰는 버튼을 누르면, 글목록 하위에 form 이 나오도록 jade 템플릿 변경

 

새 글을 쓰고 나서, 글을 제대로 썼는지 작성된 글 페이지로 '리다이렉션' 하여 이동.

res.redirect( 경로 ) 함수를 이용 

 

작성 후에 바로 작성내용을 볼 수 있다. 


app_file.js 

// 파일로 만든 웹앱 (03-15)

var express = require('express');
var app = express();
var bodyParser = require('body-parser')
var fs = require('fs')

// POST 방식 처리할 때, body 속성을 가공해준다 
app.use(bodyParser.urlencoded({extended: false}))

//템플릿 엔진 (views 들을 위치할 디렉토리 적어준다)
app.set('views', './views_file');
//템플릿 엔진 종류 명시 
app.set('view engine', 'jade');

app.locals.pretty = true;

app.get('/topic/new', function(req, res){
    res.render('new');
})


app.get(['/topic', '/topic/:id'], function(req,res){

    // 글 목록 보이기 
    fs.readdir('data', function(err,files){
        if(err){
            console.log(err);
            res.status(500).send('Internal Server Error')
        }
        var id = req.params.id

        // id 값이 있는지 없는지! 
        if(id){
            fs.readFile('data/'+id, 'utf8', function(err, data){
                // 파일 내용을 가져옵니다. 
                if(err){
                    console.log(err);
                    res.status(500).send('Internal Server Error')
                }
                // render 인자 : 템플릿파일명, 주입하려는 객체 
                // 파일목록, 제목, 내용
                res.render('view', {topics:files, title: id, description:data});
            })
        }else{ // id 값이 없으면, 
            res.render('view', {topics:files, title:'Welcome', description:'hello'})
        }
    })


})


// POST 처리
app.post('/topic',function(req, res){
    var title = req.body.title
    var description = req.body.description
    fs.writeFile('data/'+title, description, function(err){
        if(err){
            console.log(err)
            res.status(500).send('Internal Server Error')
        }// 콜백함수 실행완료 후에 응답 가능하므로, res.send 가 여기에 위치.
        res.send('Success!')
    });
})

// 애플리케이션이 특정 포트를 listen() 하도록.
app.listen(3000, function(){
    console.log('Connected 3000 port ! ');
}) 

 

view.jade

홈버튼과 새글쓰기 버튼을 추가함 

doctype html
html
    head
        meta(charset='utf-8')
    body
        h1
            a(href='/topic') Server Side JavaScript
        ul  
            each topic in topics
                li
                    a(href='/topic/'+topic)=topic
        article
            h2=title
            =description

        
        div 
            a(href='/topic/new') new

 

new.jade 

doctype html
html
    head
        meta(charset='utf-8')
    body
        h1
            a(href='/topic') Server Side JavaScript
        ul  
            each topic in topics
                li
                    a(href='/topic/'+topic)=topic

        article
            form(action='/topic', method='post')
                p
                    input(type='text' name='title' placeholder='title')
                p
                    textarea(name='description')
                p
                    input(type='submit')

                

 

728x90

'프로그래밍 > Node.js' 카테고리의 다른 글

MySQL 사용  (0) 2020.03.18
MySQL 설치  (0) 2020.03.16
본문 읽기 - 전체 코드 포함  (0) 2020.03.16
글 목록 만들기  (0) 2020.03.16
POST방식 GET방식  (0) 2020.03.15

+ Recent posts