简体   繁体   中英

API GET Response is not working in front-end

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM