简体   繁体   中英

I am working in an ecommerce project using react.I am not able to fetch products from backend using the axios

Below are the files as server.js, HomeScreen.js, pacKAGE.JSON and App.js file. Not able to see anything in this path too: http://localhost:5000/api/products Getting the error as "Cannot GET /api/products. localhost:5000 is running fine. Below are the files as server.js, HomeScreen.js, pacKAGE.JSON and App.js file. Not able to see anything in this path too: http://localhost:5000/api/products Getting the error as "Cannot GET /api/products. Below are the files as server.js, HomeScreen.js, pacKAGE.JSON and App.js file. Not able to see anything in this path too: http://localhost:5000/api/products Getting the error as "Cannot GET /api/products. Below are the files as server.js, HomeScreen.js, pacKAGE.JSON and App.js file. Not able to see anything in this path too: http://localhost:5000/api/products Getting the error as "Cannot GET /api/products. Below are the files as server.js, HomeScreen.js, pacKAGE.JSON and App.js file. Not able to see anything in this path too: http://localhost:5000/api/products Getting the error as "Cannot GET /api/products.

Server.js file

const express = require("express");
const products = require("./data/products");
const cors = require("cors");


const app = express()

app.use(cors());
app.get("/", (req, res) => {

    res.send("API is running...")
})

app.get("/api/products/:id", (req, res) => {
    const product = products.find(p => p._id === req.params.id)
    res.json(product)
})

app.listen(5000, () => {

    console.log("Server running on port 5000")
})

HomeScreen.js file

 import React, {useState, useEffect} from 'react'
 import { Row, Col } from "react-bootstrap"
 import Product from "../components/Product"
 import axios from "axios"


    const HomeScreen = () => {

const [products, setProducts] = useState([])

useEffect(() => {
    console.log("Hello")
    const fetchProducts = async () => {
        const {
            data
        } = await axios.get('http://localhost:5000/api/products')
        console.log(data);

        setProducts(data);
    }
    fetchProducts()
}, [])

return (
    <>
     <h1>Latest Products</h1>
     <Row>
           {products.map((product) => (

               <Col key = {product._id} sm = {12} md = {6} lg = {4} xl = {3}>
               <Product product = {product} />
               </Col>
           )


           )}
     </Row>
    </>
    )
   }

  export default HomeScreen

package.json file(frontend)

{
 "name": "frontend",
"proxy": "http://localhost:5000",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.9",
"@testing-library/react": "^11.2.5",
"@testing-library/user-event": "^12.8.1",
"axios": "^0.21.1",
"react": "^17.0.1",
"react-bootstrap": "^1.5.1",
"react-dom": "^17.0.1",
"react-router-bootstrap": "^0.25.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.0"
 },
 "scripts": {
 "start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
 },

App.js file

import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import { Container } from "react-bootstrap";
import Header from "./components/Header";
import Footer from "./components/Footer";
import HomeScreen from "./screens/HomeScreen";
import ProductScreen from "./screens/ProductScreen";


 const App = () =>  {
 return (
 <Router>
 <Header />
 <main className = "py-3">
  <Container>
  <Route path = "/" component = {HomeScreen} exact />
  <Route path = "/product/:id" component = {ProductScreen} />
  </Container>

 </main>
 <Footer/>
 </ Router>
 )
 }

export default App;

You need to add a get route for "/api/products". If "products.find" return a promise and it should be handled.

app.get("/api/products", async (req,res) => {
    try { 
     const product = await products.find();
     res.json(product);
  } catch(e) {
    //handle the error here  
 }
})
app.get("/api/products/:id", (req, res) => {
    products.find({id:req.params.id}).exec(function(err, product) {
      if (err) {
          console.log(err);
      } else {
          const product = res.json(product);
      }
  })
});

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