Node.js®는 Chrome V8 JavaScript 엔진으로 빌드된 JavaScript 런타임입니다.
$ npm i express
var express = require('express')
var app = express()
라우팅은 URI(또는 경로) 및 특정한 HTTP 요청 메소드(GET, POST 등)인 특정 엔드포인트에 대한 클라이언트 요청에 애플리케이션이 응답하는 방법을 결정하는 것
각 라우트는 하나 이상의 핸들러 함수를 가질 수 있으며, 이러한 함수는 라우트가 일치할 때 실행됨
app.get('/', function (req, res) {
res.send('Hello World!');
});
api | 기능 |
---|---|
app.get(path,callback[,callback]) | 해당 path의 get 요청(가져오기) 을 받아 callback 함수로 처리 |
app.post(path, callback [, callback ...]) | 해당 path의 post 요청(생성) 을 받아 callback 함수로 처리 |
app.put(path, callback [, callback ...]) | 해당 path의 put 요청(수정) 을 받아 callback 함수로 처리 |
app.delete(path, callback [, callback ...]) | 해당 path의 delete 요청(삭제) 을 받아 callback 함수로 처리 |
res.send([body]) | http response를 전송, body parameter로 Buffer object,String, object, Boolean,Array 가능 |
res.status(status code) | 응답으로 http status code를 전송 |
res.json({key:value}) | 응답을 json 형식으로 전송 |
$ npm i express
//app.js
const http = require('http');
const app = express()
app.get('/',(req,res)=>{
res.send('hello express');
})
app.get('/api/user',(req,res)=>{
res.json('hi,user')
})
app.listen(3065,()=>{
console.log('서버 실행 중')
});
api 별로 파일 분리
각 모듈에 router 설정, exports
const router = exporess.Router()
router.get(path,callbackFunction)
// post.js
const express = require('express');
const router = express.Router()
router.get('/',(req,res)=>{
res.json([
{id:1,content:'hello'},
{id:2,content:'hello2'},
{id:3,content:'hello3'},
])
})
router.post('/',(req,res)=>{
res.json({
id:1,
content:'랄랄라'
})
})
router.delete('/api/post',(req,res)=>{
})
module.exports = router;
app.use(path, router)
📑 reference