웹 프로그래밍

[Yelpcamp 프로젝트] flash

미안하다 강림이 좀 늦었다 2023. 11. 29. 18:38

 

 

 

설치

npm i connect-flash

 

 

미들웨어 추가

flash는 session을 사용하므로 app.use(session ... ) 뒤에 넣어야 합니다.

캠핑장 생성하거나 수정 등등을 할 때 req.flash(키값, 메시지)를 하면 메시지가 res.locals의 속성으로 설정이 되어서 flash.ejs로 변수들을 보낼 수 있습니다.

res.locals의 property들은 request의 라이프 타임 동안만 유효합니다.

 

app.js

const flash = require('connect-flash');

app.use(flash());
app.use((req, res, next) => {
    res.locals.success = req.flash('success');
    res.locals.error = req.flash('error');
    next();
})

 

 

 

flash 메시지 띄우기

routes/campgrounds.js에서 req.flash(키값, 메시지)로 메시지를 설정합니다.

success와 error가 res.locals의 속성으로 설정되어있으니 flash.ejs에서 success와 error에 접근할 수 있습니다.

 

routes/campground.js

const flash = require('connect-flash');

router.post('/', validateCampground, catchAsync(async (req, res) => {
    const camp = new Campground(req.body.campground);
    await camp.save();
    req.flash('success', '캠핑장을 성공적으로 생성했습니다.');
    res.redirect('/campgrounds');
}))

router.get('/:id', catchAsync(async (req, res) => {
    const camp = await Campground.findById(req.params.id).populate('reviews');
    if (!camp) {
        req.flash('error', '존재하지 않는 캠핑장입니다.');
        return res.redirect('/campgrounds');
    }
    res.render('show', { camp });
}))

router.get('/:id/edit', catchAsync(async (req, res) => {
    const camp = await Campground.findById(req.params.id);
    if (!camp) {
        req.flash('error', '존재하지 않는 캠핑장입니다.');
        return res.redirect('/campgrounds');
    }
    res.render('edit', { camp });
}))

router.put('/:id', validateCampground, catchAsync(async (req, res) => {
    const camp = await Campground.findByIdAndUpdate(req.params.id, req.body.campground);
    if (!camp) {
        req.flash('error', '존재하지 않는 캠핑장입니다.');
        return res.redirect('/campgrounds');
    }
    req.flash('success', '캠핑장을 성공적으로 수정했습니다.');
    res.redirect(`/campgrounds/${camp.id}`);
}))

router.delete('/:id', catchAsync(async (req, res) => {
    await Campground.findByIdAndDelete(req.params.id);
    req.flash('success', '캠핑장을 성공적으로 삭제했습니다.');
    res.redirect('/campgrounds');
}))

flash.ejs

<% if (success.length) {%>
    <div class="alert alert-success alert-dismissible fade show mt-3" role="alert">
        <strong><%= success %></strong>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<% } %>

<% if (error.length) {%>
    <div class="alert alert-danger alert-dismissible fade show mt-3" role="alert">
        <strong><%= error %></strong>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<% } %>

boilerplate.ejs

아래 코드 main 안에 낑궈넣기

<%- include('./partials/flash') %>

 

캠핑장 생성
캠핑장 id 잘못입력했을 경우