GET과 POST는 다음과 같이 사용할 수 있다.
import express from "express"
const app = express
app.post(URL, (req, res) => {
res.send("something") // 요청에 응답시키는 send 메소드
})
app.get(URL, (req, res) => {
res.send("something")
})
app.all(URL, (req, res) => { // all을 하면 들어오는 값에 맞는 HTTP를 매칭시켜준다.
res.send("something")
})
피라미터에 res 다음에 next를 넣으면 미들웨어를 실행 시킬 수 있다.
express의 서버는 다음과 같이 실행할 수 있다.
app.listen(PORT, HandleFunc) // PORT를 지정하면 해당 포트로 들어오는 응답을 받을 수 있다.
요청받은 응답을 보내는 방법은 다음으로 나뉜다.
app.get('/', (req,res) => {
res.send({"name" : "소녀시대"}) // JSON파일 응답
res.status(400).send({"message":"UNAVAILABLE VALUE"}) //이런식으로 status 코드를 전달
})
미들웨어는 클라이언트로부터 요청이 들어왔을 때에 응답으로 처리 하기 까지의 순차적으로 거치는 모듈이나 함수들을 말한다. 순차적으로 실행된 뒤 마지막 응답으로 보내는 과정이다.
app.use((req, res, next) => {
consol.log("첫 번째 미들웨어에서 요청을 처리함")
})
app.get('/', (req, res) => {
res.status(200).send("Succes")
})
/* 미들웨어에 있는 next 피라미터는 다음 미들웨어에게 자신의 결과를 넘겨주고 실행시켜주는
피라미터로 만약 아래에 app.use로 또 다른 미들웨어가 있다면 그 미들웨어가 가동이 된다.
*/
express는 다음의 형태로 URL로 오는 쿼리스트링과 Body 그리고 header를 확인 할 수 있다.
app.use((req, res, next) => {
const userToken = req.header('authentication')
})
app.use((req, res, next) => {
const qs = req.query.키값
// 만약 ?name=1 이라는 쿼리스트링을 가지고 있는 URL이 온다면 req.query.name으로 처리
})
app.use((req, res, next) => {
const body = req.body //body-parser필요
})
예제: body-parser와 try-catch를 이용한 POST HTTP 메서드 JSON 받기
import express from "express";
import bodyParser from "body-parser";
const app = express();
const handlerServer = () => {
console.log("<http://localhost:4000> ON");
};
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/", (req, res) => {
try {
const body = req.body;
console.log(body);
} catch (e) {
throw e.Error;
} finally {
res.status(200).send("Hello JSON");
}
});
app.listen(4000, handlerServer);
expree는 서버에 담겨있는 정적인 파일들(image, HTML ..etc)를 해당 폴더로 연결시켜줘서 넘겨주게 할 수 있다.
app.use('URL주소', static('폴더이름'));
// 이렇게 하면 해당 주소 + / 폴더에 있는 파일 이름 ex: 1.jpg에 접속하면 해당 파일을 보여준다.