0

I'm working in a React app where I want to get data from an Express server. Getting this error on the browser's console:

GET http://localhost:3000/api/products 404 (Not Found)

under this error, it says:

dispatchXhrRequest  @   xhr.js:177
xhrAdapter  @   xhr.js:13
dispatchRequest @   dispatchRequest.js:52
Promise.then (async)        
request @   Axios.js:61
Axios.<computed>    @   Axios.js:76
wrap    @   bind.js:9
(anonymous) @   productActions.js:8
(anonymous) @   index.js:8
dispatch    @   VM69:14608
(anonymous) @   HomeScreen.js:18
invokePassiveEffectCreate   @   react-dom.development.js:23487
callCallback    @   react-dom.development.js:3945
invokeGuardedCallbackDev    @   react-dom.development.js:3994
invokeGuardedCallback   @   react-dom.development.js:4056
flushPassiveEffectsImpl @   react-dom.development.js:23574
unstable_runWithPriority    @   scheduler.development.js:468
runWithPriority$1   @   react-dom.development.js:11276
flushPassiveEffects @   react-dom.development.js:23447
(anonymous) @   react-dom.development.js:23324
workLoop    @   scheduler.development.js:417
flushWork   @   scheduler.development.js:390
performWorkUntilDeadline    @   scheduler.development.js:157

What is going on? Something related to the route api/products is not working but I havw no idea what that could be.

This is my server.js file

require("dotenv").config();
const express = require("express");
const productRoutes = require("./routes/productRoutes");
const connectDB = require("./config/db");

connectDB();

const app = express();

app.use(express.json());

app.get("/", (req, res) => {
    res.json({ message: "API running..." });
});

app.use("/api/products", productRoutes);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

productRoutes.js file

const express = require("express");
const router = express.Router();
const {
    getProducts,
    getProductById,
} = require("../controller/productControllers");

router.get("/", getProducts);
router.get("/:id", getProductById);

module.exports = router;

productControllers.js file:

const Product = require("../models/Product");

const getProducts = async (req, res) => {
    try {
        const products = await Product.find({});
        res.json(products);
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: "Server Error" });
    }
};

const getProductById = async (req, res) => {
    try {
        const product = await Product.findById(req.params.id);

        res.json(product);
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: "Server Error" });
    }
};

module.exports = {
    getProducts,
    getProductById,
};

EDIT

The client code where I send the request:

import * as actionTypes from "../constants/productConstants";
import axios from "axios";

    export const getProducts = () => async (dispatch) => {
        try {
            dispatch({ type: actionTypes.GET_PRODUCTS_REQUEST });
    
            const { data } = await axios.get("/api/products");
    
            dispatch({
                type: actionTypes.GET_PRODUCTS_SUCCESS,
                payload: data,
            });
        } catch (error) {
            dispatch({
                type: actionTypes.GET_PRODUCTS_FAIL,
                payload:
                    error.response && error.response.data.message
                        ? error.response.data.message
                        : error.message,
            });
        }
    };
5
  • 1
    What's a port number that your Express server is listening to? Is it 3000, or 5000 (as specified as a default port number in your code) Commented Jun 12, 2021 at 15:25
  • I wanted it to be 5000, that is what I wrote in my server and my env diles. I don't know why the error message says "GET localhost:3000/api/products 404 (Not Found)" Commented Jun 12, 2021 at 18:12
  • 1
    Can you post the client code where you send the request? @MrFacundo Commented Jun 12, 2021 at 19:10
  • Of course. It's now on the question Commented Jun 12, 2021 at 19:20
  • In the meantime, I tried to guess what can be the cause, the third point in my answer is your case :) Commented Jun 12, 2021 at 19:21

1 Answer 1

1
  • Firstly, make sure your server is running on port 5000. You can check it by reading the log Server running on port ...

  • Then, you can do a simple test in Postman to make sure the server and the route work correctly.

  • If the 2 things above work, this is likely a problem on the client-side for me. Somewhere in your client code, you're sending a request like this :

fetch('/api/products')

It could be axios or another syntax/library. The important is by specifying only '/api/products', the request will be sent to the current host. And the React application is hosted on localhost:3000, that's why you have the error.

In this case, you should provide the full URL (I adapted the syntax based on your client code) :

 const { data } = await axios.get("http://localhost:5000/api/products");
Sign up to request clarification or add additional context in comments.

3 Comments

Nice, changing this line made the request go to port 5000. Now I have this issue :( Failed to load resource: net::ERR_CONNECTION_REFUSED
You may need to add more detail in your question about the new error. Based on your setup, I think it could be an issue with CORS
Indeed. The first answer in the link solved the issue. Also, my server was not working properly due to an error in the .env file: PORT=5000; instead of PORT=5000

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.