skip to Main Content

The code works well in Postman. But when fetching it in the front-end the response is not working. I can’t find the solution. I am new in MERN stack. It gives me error.
product.action.js:7 Uncaught (in promise) AxiosError {message: 'timeout of 1000ms exceeded', name: 'AxiosError', code: 'ECONNABORTED', config: {…}, request: XMLHttpRequest}
The back end code :- router.get("/products/:slug", getProductsBySlug);

    exports.getProductsBySlug = (req, res) => {
  const { slug } = req.params;
  Category.findOne({ slug: slug })
    .select("_id")
    .exec((error, category) => {
      if (error) {
        return res.status(400).json({ error });
      }
      if (category) {
        Product.find({ category: category._id }).exec((error, products) => {
          if (error) {
            return res.status(400).json({ error });
          }
          res.status(200).json({ products });
        });
      }
    });
};

Front end code: product.action.js

    import axiosInstance from "../helpers/axios";

export const getProductsBySlug = (id) => {
  return async (dispatch) => {
    const res = await axiosInstance.get(`/products/${id}`);
    console.log(res);
  };
};

`
The above response is occure error.

`
productListPage:

import React, { useEffect } from "react";
    import { useDispatch } from "react-redux";
    import { getProductsBySlug } from "../../actions";
    import Layout from "../../components/Layout";
    import { useParams } from "react-router-dom";

    const ProductListPage = (props) => {
      const dispatch = useDispatch();
      const slug = useParams();
      useEffect(() => {
        console.log(slug);
        dispatch(getProductsBySlug(slug));
      }, []);
      return <Layout>Product List Page</Layout>;
};

   export default ProductListPage;

In App.js

 function App() {
      return (
        <div className="App">
      <BrowserRouter>
        <Routes>
          <Route path="/" exact element={<HomePage />} />
          <Route path=":slug" element={<ProductListPage />} />
        </Routes>
      </BrowserRouter>
    </div>
  );

Tell me the way please.

2

Answers


  1. In your App.js, change the Route declaration to (add the leading /):

    <Route path="/:slug" element={<ProductListPage />} />
    

    In your productListPage component, you should deconstruct the property from useParams:

    const { slug } = useParams();
    
    Login or Signup to reply.
  2. Clear the local storage key/value things, should be working.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search