Created
June 30, 2016 15:41
간단한 Express 사용 에제
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var morgan = require('morgan'); // 서버 로그 콘솔에 기록 | |
var bodyParser = require('body-parser'); // JSON 형태 데이터 파싱 | |
// EXPRESS 생성 | |
var app = express(); | |
// 3rd party middleware 적용 | |
app.use(morgan('dev')); | |
app.use(bodyParser.json()); | |
// 루트 페이지 | |
app.get('/', function(req, res) { | |
res.send('Welcome to Codelab'); | |
}); | |
// 정적 파일 제공 | |
app.use('/', express.static('public')); | |
// 라우터 사용 | |
var user = require('./router/user'); | |
app.use('/user', user); | |
// 서버 열기 | |
app.listen(3000, function() { | |
console.log('Example App listening on port 3000'); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "express-tutorial", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"start": "node main.js" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"body-parser": "^1.15.2", | |
"express": "^4.14.0" | |
}, | |
"devDependencies": { | |
"morgan": "^1.7.0" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
router/user.js | |
*/ | |
var router = require('express').Router(); | |
router.get('/:id', function(req, res) { | |
res.send('Received a GET request, param:' + req.params.id); | |
}); | |
router.post('/', function(req, res) { | |
console.log(req.body); | |
console.log(req.body.username); | |
res.json({ success: true }); | |
}); | |
router.put('/', function(req, res) { | |
res.send('Received a PUT request'); | |
}); | |
router.delete('/', function(req, res) { | |
res.send('Received a DELETE request'); | |
}); | |
module.exports = router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment