반응형
react redis 연동
react redis 연동을 위해서 백엔드 처리도 있지만 일단 redis 백엔드 서버로 등록하여 처리 방법입니다.
react backend 프로젝트 생성
프로젝트 디렉터리 생성 및 초기화합니다.
- visual studio code로 신규 폴더를 오픈합니다.
- 터미널에서 "npm init -y"를 실행합니다.
필요한 패키지 설치
필요한 패키지를 설치합니다.
Express, Redis, Body-parser, CORS 패키지를 설치합니다.
- 터미널에서 "npm install express redis body-parser cors" 실행합니다.
설치 완료
- 패키지 설치까지 끝나면 위와 같은 모습입니다.
server.js 파일 생성
package.json 와 같은 위치에 server.js 파일을 생성합니다.
아래 코드처럼 작성합니다.
server.js 소스
const express = require('express');
const redis = require('redis');
const bodyParser = require('body-parser');
const cors = require('cors');
// CORS 옵션 설정
const corsOptions = {
//origin: 'https://example.com', // 특정 도메인만 허용
origin: (origin, callback) => {
console.log('origin : ' + origin);
if (['http://127.0.0.1:3000', 'http://localhost:3000',
'https://127.0.0.1:3000', 'https://localhost:3000'].indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: 'GET,POST,PUT,DELETE', // 허용할 HTTP 메서드
allowedHeaders: 'Content-Type,Authorization', // 허용할 헤더
exposedHeaders: 'Content-Length,Content-Type', // 클라이언트가 접근할 수 있는 응답 헤더
credentials: true, // 쿠키 및 인증 헤더 허용
maxAge: 86400 // 프리플라이트 요청 캐시 시간 (24시간)
};
const app = express();
const port = 5000;
app.use(bodyParser.json());
app.use(cors(corsOptions));
// Redis 클라이언트 생성 및 연결
const client = redis.createClient({
url: 'redis://:hoho@127.0.0.1:6379' // 비밀번호가 있는 경우
//url: 'redis://127.0.0.1:6379' // 비밀번호가 없는 경우
});
client.on('connect', () => {
console.log('Connected to Redis');
});
client.on('error', (err) => {
console.error('Redis error: ', err);
});
// 데이터 설정 라우트
app.post('/data', async (req, res) => {
const { key, value } = req.body;
try {
await client.set(key, value);
res.json({ message: 'OK' });
} catch (err) {
res.status(500).json({ error: err.toString() });
}
});
// 데이터 가져오기 라우트 (키를 쿼리 파라미터로 받음)
app.get('/data', async (req, res) => {
const key = req.query.key; // 쿼리 파라미터에서 키를 가져옴
try {
const value = await client.get(key);
if (value === null) {
return res.status(404).json({ error: 'Key not found' });
}
//res.json({ key, value });
res.send(value);
} catch (err) {
res.status(500).json({ error: err.toString() });
}
});
// 데이터 가져오기 라우트
app.post('/data-post', async (req, res) => {
const key = req.body.key;
try {
const value = await client.get(key);
if (value === null) {
return res.status(404).json({ error: 'Key not found' });
}
//res.json({ key, value });
res.send(value);
} catch (err) {
res.status(500).json({ error: err.toString() });
}
});
// JSON 데이터 설정 라우트
app.post('/json-data', async (req, res) => {
const { key, jsonData } = req.body;
try {
const jsonString = JSON.stringify(jsonData); // JSON 데이터를 문자열로 변환
await client.set(key, jsonString);
res.json({ message: 'JSON data saved' });
} catch (err) {
res.status(500).json({ error: err.toString() });
}
});
// JSON 데이터 가져오기 라우트
app.get('/json-data', async (req, res) => {
const key = req.query.key;
try {
const jsonString = await client.get(key);
if (jsonString === null) {
return res.status(404).json({ error: 'Key not found' });
}
const jsonData = JSON.parse(jsonString); // 문자열을 JSON 객체로 변환
res.json({ key, jsonData });
} catch (err) {
res.status(500).json({ error: err.toString() });
}
});
// JSON 데이터 가져오기 라우트
app.post('/json-data-post', async (req, res) => {
const key = req.body.key;
try {
const jsonString = await client.get(key);
if (jsonString === null) {
return res.status(404).json({ error: 'Key not found' });
}
const jsonData = JSON.parse(jsonString); // 문자열을 JSON 객체로 변환
res.json({ key, jsonData });
} catch (err) {
res.status(500).json({ error: err.toString() });
}
});
// Hash 데이터 설정 라우트
app.post('/hash-data', async (req, res) => {
const { key, field, value } = req.body;
try {
await client.hSet(key, field, value);
res.json({ message: 'Hash data saved' });
} catch (err) {
res.status(500).json({ error: err.toString() });
}
});
// Hash 데이터 가져오기 라우트
app.get('/hash-data', async (req, res) => {
const { key, field } = req.query;
try {
const value = await client.hGet(key, field);
if (value === null) {
return res.status(404).json({ error: 'Field not found in hash' });
}
res.json({ key, field, value });
} catch (err) {
res.status(500).json({ error: err.toString() });
}
});
// Hash 데이터 가져오기 라우트
app.post('/hash-data-post', async (req, res) => {
const { key, field } = req.body;
try {
const value = await client.hGet(key, field);
if (value === null) {
return res.status(404).json({ error: 'Field not found in hash' });
}
res.json({ key, field, value });
} catch (err) {
res.status(500).json({ error: err.toString() });
}
});
// Hash 데이터 전체 가져오기 라우트
app.get('/hash-all', async (req, res) => {
const key = req.query.key;
try {
const hashData = await client.hGetAll(key);
if (Object.keys(hashData).length === 0) {
return res.status(404).json({ error: 'Hash not found' });
}
res.json({ key, hashData });
} catch (err) {
res.status(500).json({ error: err.toString() });
}
});
// Hash 데이터 전체 가져오기 라우트
app.post('/hash-all-post', async (req, res) => {
const key = req.body.key;
try {
const hashData = await client.hGetAll(key);
if (Object.keys(hashData).length === 0) {
return res.status(404).json({ error: 'Hash not found' });
}
res.json({ key, hashData });
} catch (err) {
res.status(500).json({ error: err.toString() });
}
});
app.listen(port, async () => {
await client.connect(); // Redis 클라이언트를 연결
console.log(`Server is running on port ${port}`);
});
local에서 래딧을 실행한 상태에서 "npm start"를 실행합니다.
Connected to Redis
Server is running on port 5000
위와 같은 로그가 나오면 래딧에 정상적으로 접속이 된 겁니다.
여기까지 래딧 실행 >> 백엔드 실행입니다.
react 접속 코드
- 아래 소스를 적용하여 접속하시면 됩니다.
- fatchData : string get 호출
- fatchDataPost : string post 호출
- fetchJsonData : json get 호출
- fetchJsonDataPost : json post 호출
- fetchHashData : hash get 호출
- fetchHashDataPost : hash post 호출
- fetchAllHashData : 지정한 hash 모두 get 호출
- fetchAllHashData Post : 지정한 hash 모두 post 호출
- handleSubmit : string post 저장
- handleJsonSubmit : json post 저장
- handleHashSubmit : hash post 저장
import React, { useState } from 'react';
import axios from 'axios';
const Main5 = () => {
const [data, setData] = useState('');
const [inputKey, setInputKey] = useState('');
const [inputValue, setInputValue] = useState('');
const [jsonData, setJsonData] = useState('');
const [hashField, setHashField] = useState('');
const [hashValue, setHashValue] = useState('');
const fetchData = () => {
axios.get('http://localhost:5000/data', { params: { key: inputKey } })
.then(response => {
//const { key, value } = response.data;
//setData(`Key: ${key}, Value: ${value}`);
setData(response.data);
})
.catch(error => {
console.error('There was an error!', error);
setData(''); // 에러 발생 시 데이터 초기화
});
};
const fetchDataPost = () => {
axios.post('http://localhost:5000/data-post', { key: inputKey } )
.then(response => {
//const { key, jsonData } = response.data;
//setData(`Key: ${key}, Value: ${JSON.stringify(jsonData)}`);
setData(response.data);
})
.catch(error => {
console.error('There was an error!', error);
setData(''); // 에러 발생 시 데이터 초기화
});
};
const fetchJsonData = () => {
axios.get('http://localhost:5000/json-data', { params: { key: inputKey } })
.then(response => {
const { key, jsonData } = response.data;
setData(`Key: ${key}, JSON Data: ${JSON.stringify(jsonData)}`);
})
.catch(error => {
console.error('There was an error!', error);
setData(''); // 에러 발생 시 데이터 초기화
});
};
const fetchJsonDataPost = () => {
axios.post('http://localhost:5000/json-data-post', { key: inputKey } )
.then(response => {
const { key, jsonData } = response.data;
setData(`Key: ${key}, JSON Data: ${JSON.stringify(jsonData)}`);
})
.catch(error => {
console.error('There was an error!', error);
setData(''); // 에러 발생 시 데이터 초기화
});
};
const fetchHashData = () => {
axios.get('http://localhost:5000/hash-data', { params: { key: inputKey, field: hashField } })
.then(response => {
const { key, field, value } = response.data;
setData(`Key: ${key}, Field: ${field}, Value: ${value}`);
})
.catch(error => {
console.error('There was an error!', error);
setData(''); // 에러 발생 시 데이터 초기화
});
};
const fetchHashDataPost = () => {
const jsonPayload = {
key: inputKey,
field: hashField // 문자열을 JSON 객체로 변환
};
axios.post('http://localhost:5000/hash-data-post', jsonPayload)
.then(response => {
const { key, field, value } = response.data;
setData(`Key: ${key}, Field: ${field}, Value: ${value}`);
})
.catch(error => {
console.error('There was an error!', error);
setData(''); // 에러 발생 시 데이터 초기화
});
};
const fetchAllHashData = () => {
axios.get('http://localhost:5000/hash-all', { params: { key: inputKey } })
.then(response => {
const { key, hashData } = response.data;
setData(`Key: ${key}, Hash Data: ${JSON.stringify(hashData)}`);
})
.catch(error => {
console.error('There was an error!', error);
setData(''); // 에러 발생 시 데이터 초기화
});
};
const fetchAllHashDataPost = () => {
const jsonPayload = {
key: inputKey,
field: hashField // 문자열을 JSON 객체로 변환
};
axios.post('http://localhost:5000/hash-all-post', jsonPayload)
.then(response => {
const { key, hashData } = response.data;
setData(`Key: ${key}, Hash Data: ${JSON.stringify(hashData)}`);
})
.catch(error => {
console.error('There was an error!', error);
setData(''); // 에러 발생 시 데이터 초기화
});
};
const handleInputKeyChange = (e) => {
setInputKey(e.target.value);
};
const handleInputValueChange = (e) => {
setInputValue(e.target.value);
};
const handleJsonDataChange = (e) => {
setJsonData(e.target.value);
};
const handleHashFieldChange = (e) => {
setHashField(e.target.value);
};
const handleHashValueChange = (e) => {
setHashValue(e.target.value);
};
const handleKeyPress = (e) => {
if (e.key === 'Enter') {
fetchData();
}
};
const handleSubmit = () => {
const jsonData = {
key: inputKey,
value: inputValue
};
axios.post('http://localhost:5000/data', jsonData)
.then(response => {
console.log('Data set:', response.data);
setData(`Key: ${inputKey}, Value: ${inputValue}`); // 상태 업데이트
})
.catch(error => {
console.error('There was an error!', error);
});
};
const handleJsonSubmit = () => {
const jsonPayload = {
key: inputKey,
jsonData: JSON.parse(jsonData) // 문자열을 JSON 객체로 변환
};
axios.post('http://localhost:5000/json-data', jsonPayload)
.then(response => {
console.log('JSON data set:', response.data);
setData(`Key: ${inputKey}, JSON Data: ${jsonData}`); // 상태 업데이트
})
.catch(error => {
console.error('There was an error!', error);
});
};
const handleHashSubmit = () => {
const hashPayload = {
key: inputKey,
field: hashField,
value: hashValue
};
axios.post('http://localhost:5000/hash-data', hashPayload)
.then(response => {
console.log('Hash data set:', response.data);
setData(`Key: ${inputKey}, Field: ${hashField}, Value: ${hashValue}`); // 상태 업데이트
})
.catch(error => {
console.error('There was an error!', error);
});
};
return (
<div className="App">
<h1>Redis Data</h1>
<div>
<input
type="text"
placeholder="Enter key"
value={inputKey}
onChange={handleInputKeyChange}
onKeyPress={handleKeyPress}
/>
<button onClick={fetchData}>Fetch Data</button>
<button onClick={fetchDataPost}>Fetch Data Post</button>
<button onClick={fetchJsonData}>Fetch JSON Data</button>
<button onClick={fetchJsonDataPost}>Fetch JSON Data Post</button>
<button onClick={fetchHashData}>Fetch Hash Data</button>
<button onClick={fetchHashDataPost}>Fetch Hash Data Post</button>
<button onClick={fetchAllHashData}>Fetch All Hash Data</button>
<button onClick={fetchAllHashDataPost}>Fetch All Hash Data Post</button>
</div>
<div>
<p>Value: {data}</p>
</div>
<div>
<input
type="text"
placeholder="Enter value"
value={inputValue}
onChange={handleInputValueChange}
/>
<button onClick={handleSubmit}>Set Data</button>
</div>
<div>
<textarea
placeholder="Enter JSON data"
value={jsonData}
onChange={handleJsonDataChange}
/>
<button onClick={handleJsonSubmit}>Set JSON Data</button>
</div>
<div>
<input
type="text"
placeholder="Enter hash field"
value={hashField}
onChange={handleHashFieldChange}
/>
<input
type="text"
placeholder="Enter hash value"
value={hashValue}
onChange={handleHashValueChange}
/>
<button onClick={handleHashSubmit}>Set Hash Data</button>
</div>
</div>
);
}
export default Main5;
※ react에서 백엔드(node.js)를 활용한 래딧 접속 방법입니다.
반응형
'db > redis' 카테고리의 다른 글
redis config 패스워드 설정 windows (0) | 2024.07.29 |
---|---|
Redis 다운로드 및 설치 실행 (0) | 2024.07.25 |
redis gui tool web download 설치 (0) | 2024.07.25 |
redis gui tool download(Another Redis Desktop Manager) 설치 (0) | 2024.07.25 |