- params
- Todo 예제
1) params
node에서 서버에 요청을 보낼 때 매개변수를 같이 보낼 수 있다.
아래 코드를 보면 data에 총 5개의 객체가 있고, 3000/language엔 모든 data가 출력된다.
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
const data = [
{
id: 1,
name: 'vanillascript',
price: 100,
desc: '바닐라 스크립트',
imgurl: '/images/img1.jpg'
},
{
id: 2,
name: 'node',
price: 200,
desc: '노드',
imgurl: '/images/img2.jpg'
},
{
id: 3,
name: 'swift',
price: 300,
desc: '스위프트',
imgurl: '/images/img3.jpg'
},
{
id: 4,
name: 'react',
price: 400,
desc: '리액트',
imgurl: '/images/img4.jpg'
},
{
id: 5,
name: 'typescript',
price: 500,
desc: '타입 스크립트',
imgurl: '/images/img5.jpg'
},
];
app.get('/language', (req, res) => {
res.send({
data: data
}
)
});
app.get('/language/:id', (req, res) => {
const no = Number(req.params.id);
const { id, name, price, desc, imgurl } = data[no]
res.send(`
번호 : ${id} <br/>
이름 : ${name} <br/>
가격 : ${price} <br/>
설명 : ${desc} <br/>
이미지주소 : ${imgurl}
`)
});
app.listen(port, (req, res) => {
console.log(`${port}번 서버 실행중`);
});

그리고 params를 받는 get의 경우 서버에 요청을 할 때 /language/1과 같이 요청하게 된다.
:id 자리에 매개변수가 들어가게 되는것이다.
따라서 /language/1로 요청을 하면 req.params.id가 1이 되고 no 변수에 담기게 된다.
그럼 data[1] 1번 인덱스에 관한 데이터만 출력되게 된다.

2) Todo 예제
todo 기능에는 추가/삭제/체크 총 3가지가 있는데 node를 사용해 frontend, backend 두 폴더로 나누어 수정했다.
frontend에서 수정해야 할 부분은 아래와 같다.
reducers에 들어있던 함수들을 모두 밖으로 뺀다.
export const todoSlice = createSlice({
name: 'todo',
initialState,
reducers: {
changeInput: (state, action) => {
state.text = action.payload
},
},
서버에서 데이터를 가져와 화면에 뿌려주는 getTodos, todo를 삭제하는 delTodos, 새로운 todo를 추가해 주는 putTodos 그리고 체크 기능을 하는 putTodos가 있다.
export const getTodos = createAsyncThunk(
'todos/getTodos',
async () => {
const res = await axios.get(`http://localhost:3000/todos`)
return res.data
}
)
export const delTodos = createAsyncThunk(
'todos/delTodos',
async (removeid) => {
const res = await axios.delete(`http://localhost:3000/todos/${removeid}`);
return res.data
}
)
export const postTodos = createAsyncThunk(
'todos/postTodos',
async (text) => {
const res = await axios.post(`http://localhost:3000/todos`, { text });
return res.data
}
)
export const putTodos = createAsyncThunk(
'todos/putTodos',
async (putid) => {
const res = await axios.put(`http://localhost:3000/todos/${putid}`);
return res.data
}
)
삭제를 하는 delTodos의 경우 removeid를 매개변수로 받아 해당하는 아이템을 삭제하는데 삭제 버튼을 누를 때 아이템의 id를 매개변수로 보낸다.
<button onClick={()=>dispatch(delTodos(id))}>삭제</button>
그 후에 delete와 id가 포함된 주소를 서버에 요청하게 되고 성공(fulfilled)하게 되면 slice 아래 있는 함수가 실행된다.
새로 받아온 data를 slice에 있는 state.data에 업데이트해주는 것이다.
extraReducers: (builder) => {
builder
.addCase(getTodos.fulfilled, (state, action) => {
state.data = action.payload
})
.addCase(delTodos.fulfilled, (state, action) => {
state.data = action.payload
})
이후는 backend에서 작업되는 내용이다.
삭제 기능을 하는 app.delete의 경우 /todos/:id로 id라는 매개변수를 받게 되는데 위에서 알아보았듯이 req.params.id가 되는 것이다.
filter를 이용해서 해당 매개변수가 제외된 data를 send 하게 된다.
let todos = [
{ id: 1, text: '리액트 공부', isChk: true },
{ id: 2, text: '프로젝트 계획 수립', isChk: false },
{ id: 3, text: '노드 공부', isChk: false },
{ id: 4, text: '서점 가기', isChk: true },
{ id: 5, text: '마트 가기', isChk: false }
]
app.get('/todos', (req, res) => {
res.send(todos)
})
// 삭제
app.delete('/todos/:id', (req, res) => {
todos = todos.filter(item => item.id !== Number(req.params.id))
res.send(todos)
})