먼저,
1. header.js 여기에서 쿼리를 이용해서 데이터를 받고, 성공적으로 데이터를 얻어오면
window.location.replace('/?value=' + e.target.textContent); 를 이용해서 '/' 페이지로 갑니다.
header.js 코드.
listItems.forEach((item) => {
item.addEventListener('click', function (e) {
$.ajax({
method: 'POST',
url: `/search?value=${e.target.textContent}`,
})
.done((data) => {
console.log(data);
window.location.replace('/?value=' + e.target.textContent);
})
.fail((xhr, code, err) => {
console.log(err);
});
});
});
2. 그럼 '/' 에서
const decodeUri = decodeURI(window.location?.search);
fetch({
method: 'GET',
url: `/list/${decodeUri}`,
})
를 이용해서 데이터를 받아오면 어떨까싶어서 위와같이 코드를짜봤습니다.
실제 url은 이런식으로 되어있구요
http://localhost:8080/?value=하니
3. 서버 코드는 이렇습니다.
router.get('/list', async (req, res) => {
try {
const post = await Post.find({ category: req.query.value })
.sort({ _id: 1 })
.exec();
console.log(post);
// const posts = await Post.find().sort({ date: -1 });
// res.json(posts);
res.json('dd');
} catch (error) {
console.error(error.message);
res.status(500).send('Server Error');
}
});
혹시 이렇게 진행하는게 아닌가요?
제가 생각했던대로하면 잘 되야하는데 .. 동작이 안되네요