Node.js의 GET, POST 처리

먼저 express를 이용해 다음과 같이 서버를 생성합니다.

const express = require("express");
const app = express();

const table = [
    { name: "Jack", alias: "Monkey" },
    { name: "Shelly", alias: "Cat" },
    { name: "Toms", alias: "Dog" }
];

// 여기에 GET, POST를 처리하는 코드가 추가됨

app.use(express.static(__dirname + "/static"));
app.listen(3000);

4번 코드의 table은 DB 대신 사용하는 데이터 객체입니다. 그리고 10번 코드는 static이라는 디렉토리에 test.html 파일을 넣을 것인데.. 이를 웹브라우저에서 127.0.0.1:3000/test.html 처럼 접근할 수 있도록 하기 위함입니다. 이 test.html 파일이 우리가 만들 서버에 GET, POST 요청을 하는 클라이언트에 해당하는 코드입니다.

가장 먼저 table에 저장된 사용자의 name 목록을 얻어오는 names GET 처리에 대한 코드는 다음과 같습니다. 코드 추가는 10번에 하면 됩니다.

app.get("/names", (req, res) => {
    const names = table.map(item => {
        return { name: item.name };
    });
    res.status(200).json(names);
});

test.html에 입력할 클라이언트 코드는 다음과 같구요.

const url = "http://127.0.0.1:3000/names";
fetch(url, {
    method: "GET"
}).then(response => {
    return response.text();
}).then(text => {
    const data = JSON.parse(text);
    console.log(data);
}).catch(error => {
    console.warn(error);
});

웹브라우저의 콘솔에 표시되는 실행 결과는 다음과 같습니다.

(3) [{…}, {…}, {…}]
0: {name: 'Jack'}
1: {name: 'Shelly'}
2: {name: 'Toms'}
...

이번에는 Query String을 갖는 GET 요청입니다. 이름을 받아 별칭을 그 결과로 전달하는 처리에 대한 서버 코드입니다.

app.get("/alias", (req, res) => {
    const name = req.query.name;
    const result = table.find((item) => {
        return item.name === name;
    });

    if(result) {
        res.status(200).json({ alias: result.alias });
    } else {
        res.status(200).json({});
    }
});

클라이언트 코드는 다음과 같습니다.

const url = "http://127.0.0.1:3000/alias?name=Suzan";
fetch(url, {
    method: "GET",
}).then(response => {
    return response.text();
}).then(text => {
    const data = JSON.parse(text);
    console.log(data);
}).catch(error => {
        console.warn(error);
});

결과는 다음과 같습니다.

{alias: 'Cat'}

이제 POST 호출입니다. 서버에 새로운 사람을 추가하는 서버측 코드입니다.

app.use(express.json());

app.post("/add", (req, res) => {
    const item = req.body;

    if(item.name && item.alias) {
        table.push(item);
        res.sendStatus(200);
    } else {
        res.sendStatus(400);
    }
});

위의 서비스를 이용하는 클라이언트 코드는 다음과 같습니다.

const url = "http://127.0.0.1:3000/add";
fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name: "Suzan", alias: "고슴도치" })
}).then(response => {
    console.log(response.ok);
}).catch(error => {
    console.warn(error);
});

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다