Reputation: 1178
I'm using react, nodejs and mongodb. I have a search bar that sends a post request to a search function that then querys mongodb and returns the result. The problem is that the function is never getting executed.
React:
const getData = (searchValue) => {
const ourRequest = Axios.CancelToken.source();
async function fetchPost() {
try {
const response = await Axios.post(`/search`, {
params: { searchValue },
cancelToken: ourRequest.token,
});
if (response.data) {
console.log(response.data);
} else {
dispatch({ type: 'notFound' });
}
} catch (e) {
console.log('There was a problem or the request was cancelled.');
}
}
fetchPost();
};
Express:
router.js
apiRouter.post('/search', postController.search);
postController.js
exports.search = function (req, res) {
Post.search(req.body.searchTerm)
.then((posts) => {
console.log('Hello..');
res.json(posts);
})
.catch((e) => {
res.json([]);
});
};
Post.js:
Post.search = function (searchTerm) {
return new Promise(async (resolve, reject) => {
if (typeof searchTerm == 'string') {
console.log('hello..', searchTerm) // nothing
let posts = await Post.reusablePostQuery([
{ $match: { $text: { $search: searchTerm } } },
{ $sort: { score: { $meta: 'textScore' } } },
]);
resolve(posts);
} else {
reject();
}
});
};
When I enter a search I get a empty array response in the dev console.
Upvotes: 3
Views: 105
Reputation: 7905
It's always hard to troubleshoot questions like this as there could be an issue in so many places. But I will point to a few that stand out and hopefully it will lead you to the answer.
The first thing that jumps out is this: req.body.searchTerm
. You're looking for the searchTerm
while your React app isn't sending it. Instead you're sending searchValue
as in params: { searchValue }
which translates to params: { searchValue: searchValue }
.
So you should change 2 things in your React code.
const response = await Axios({
method: 'post',
url: '/search',
data: {
searchTerm: searchValue
},
cancelToken: ourRequest.token
})
These changes, in theory, should resolve your issue.
Upvotes: 2