I'm getting a 404 error for a search route despite similarly defined routes working fine. I'm trying to search for a post via its title and/or tags. Here are my routes defined in the backend:
const router = express.Router();
router.get("/", getPosts);
router.get("/:id", getPost);
router.get("/search", getPostsBySearch);
router.post("/", auth, createPost);
router.patch("/:id", auth, updatePost);
router.patch("/:id/likePost", auth, likePost);
router.delete("/:id", auth, deletePost);
export default router
Here is my action for searching for a post:
export const getPostsBySearch = (searchQuery) => async (dispatch) => {
try {
dispatch({ type: "START_LOADING" });
const { data } = await api.fetchPostsBySearch(searchQuery);
dispatch({ type: "FETCH_BY_SEARCH", payload: data });
dispatch({ type: "END_LOADING" });
} catch (error) {
console.log(error);
}
}
And here is the api file exporting routes to the action:
const API = axios.create({ baseURL: "http://localhost:5000" });
export const fetchPosts = (page) => API.get(`/posts?page=${page}`);
export const fetchPost = (id) => API.get(`/posts/${id}`);
export const fetchPostsBySearch = (searchQuery) =>
API.get(
`/posts/search?searchQuery=${searchQuery.search || "none"}&tags=${
searchQuery.tags
}`
);
I had the :id route on top of the search route, so it was reading /search as an id, so instead of
router.get("/", getPosts);
router.get("/:id", getPost);
router.get("/search", getPostsBySearch);
it should be
router.get("/", getPosts);
router.get("/search", getPostsBySearch);
router.get("/:id", getPost);
router.get("/search", getPostsBySearch); // Route you mentioned
but you were using `/posts/search`
export const fetchPostsBySearch = (searchQuery) =>
API.get(
`/search?searchQuery=${searchQuery.search || "none"}&tags=${
searchQuery.tags
}`
);