823 viewsMern Amazona

Dear Sir,

First of all thank you for an amazing tutorial. However i got stuck on “React & Node ECommerce Tutorial For Beginners 2022 [MERN Stack ECommerce Website]” video on add product screen lesson. The link is https://www.youtube.com/watch?v=CDtPMR5y0QU. I get error Request failed with status code 404 when i click on a product to take me to ProductScreen.js. I rewatched that part of the video multiple times and I am pretty sure that my code matches yours. Do you have any idea where the problem might be? In ProductScreen.js or in server.js? I will paste the code of both files down below. Once again, thank you sir for an amazing tutorial.

[apcode language=\”jscript\”]

import axios from \'axios\';
import { useEffect, useReducer } from \'react\';
import { useParams } from \'react-router-dom\';
 const reducer = (state, action) => {
  switch (action.type) {
    case \'FETCH_REQUEST\':
      return { ...state, loading: true };
    case \'FETCH_SUCCESS\':
      return { ...state, object: action.payload, loading: false };
    case \'FETCH_FAIL\':
      return { ...state, loading: false, error: action.payload };
    default:
      return state;
  }
};
 function ObjectScreen() {
  const params = useParams();
  const { slug } = params;
   const [{ loading, error, object }, dispatch] = useReducer(reducer, {
    object: [],
    loading: true,
    error: \'\',
  });
  //const [objects, setObjects] = useState([]);
  useEffect(() => {
    const fetchData = async () => {
      dispatch({ type: \'FETCH_REQUEST\' });
      try {
        const result = await axios.get(`/api/objects/slug/${slug}`);
        dispatch({ type: \'FETCH_SUCCESS\', payload: result.data });
      } catch (err) {
        dispatch({ type: \'FETCH_FAIL\', payload: err.message });
      }
       //setObjects(result.data);
    };
    fetchData();
  }, [slug]);
   return loading ? (
    <div>Loading...</div>
  ) : error ? (
    <div>{error}</div>
  ) : (
    <div>{object.name}</div>
  );
}
 export default ObjectScreen;

[/apcode]

[apcode language=\”jscript\”]

import express from \'express\';
import data from \'./data.js\';
 const app = express();
 app.get(\'/api/objects\', (req, res) => {
  res.send(data.objects);
});
 app.get(\'/api/objects/slug/:slug\', (req, res) => {
  const object = data.objects.find((x) => x.slug === req.params.slug);
  if (object) {
    res.send(object);
  } else {
    res.status(404).send({ message: \'Restaurant not found\' });
  }
});
 const port = process.env.PORT || 5000;
app.listen(port, () => {
  console.log(`serve at http://localhost:${port}`);
});

[/apcode]

Bassir Changed status to publish November 26, 2023

Hello Ante,

I am also learning Mern. Why you use forward(\) in line 7 ( app.get(\’/api/objects/slug/:slug\’, (req, res) => {).   I think this will create a problem. I am  waiting for your response.

Best,

Fajla Rabby Khan

You are viewing 1 out of 1 answers, click here to view all answers.