반응형
목표
delete 기능을 Express을 이용해 semantic url 방식으로 작성하기
이전 코드
}else if(pathname === '/delete_process'){
var body = '';
request.on('data', function(data){
body = body + data;
});
request.on('end', function(){
var post = qs.parse(body);
// id만 받으면 된다
var id = post.id;
var filteredId = path.parse(id).base;
fs.unlink(`data/${filteredId}`, function(error){
response.writeHead(302, {Location: `/`});
response.end();
});
});
Express 코드
//7. delete 버튼 클릭 시 페이지
app.post('/delete_process', function(request, response){
var body = '';
request.on('data', function(data){
body = body + data;
});
request.on('end', function(){
var post = qs.parse(body);
// id만 받으면 된다
var id = post.id;
var filteredId = path.parse(id).base;
fs.unlink(`data/${filteredId}`, function(error){
response.writeHead(302, {Location: `/`});
response.end();
});
});
})
추가 기능
response.writeHead(302, {Location: `/`});
response.end();
다음의 response 두 문장도 Express를 이용하여 축약할 수 있다.
Google에 nodejs express redirect를 검색해보자.
How do I redirect in expressjs while passing some context?
I am using express to make a web app in node.js. This is a simplification of what I have: var express = require('express'); var jade = require('jade'); var http = require("http"); var app = expre...
stackoverflow.com
response.redirect('/');
수정2
이전 코드
response.writeHead(302, {Location: `/page/${title}`}); //302: redirection. 수정된 페이지로 이동
response.end();
수정된 코드
response.redirect(`/page/${title}`);
여기까지 이전 코드를 Express 코드로 수정하였다. 그 결과, 대부분이 라우터를 사용하였다. 따라서 어떻게 라우트할건지, path별로 어떻게 응답할 것인지, get과 post를 어떻게 구분하여 응답할건지 에 대해 잘 살펴보아야 한다.
반응형
'Back-End > Node.js' 카테고리의 다른 글
Express - 9.2. 미들웨어의 사용 - compression (0) | 2020.09.06 |
---|---|
Express - 9.1. 미들웨어의 사용 - body parser (0) | 2020.09.06 |
Express - 7. 페이지 수정 구현 (0) | 2020.09.06 |
Express - 6. 페이지 생성 구현 (0) | 2020.09.06 |
Node.js - get & post (0) | 2020.09.06 |