Getting ERR_CONNECTION_REFUSED in React and Node.js Application

I keep getting errors ShoppingCart.js:16  GET http://localhost:5001/api/cart net::ERR_CONNECTION_REFUSED and signup.js:71 POST http://localhost:5001/api/users/register net::ERR_CONNECTION_REFUSED. Im unsure what the issue is. I spent hours doing reasarch but I cant find the solution. It gives me the same type of error when i signup aswell so I assume its one big mistake i made thats affecting it all. The error occurs when I do a signup, login and when i access the shopping cart which makes me believe its a backend issue of some sort.

import { useState } from "react";
import axios from "axios";

function Login() {
    const [loginEmail, setLoginEmail] = useState('');
    const [loginPassword, setLoginPassword] = useState('');
    const [loginError, setLoginError] = useState({
        loginEmail: '',
        loginPassword: '',
        general: ''
    });
    const [loading, setLoading] = useState(false);

    const handleLoginEmailChange = (e) => {
        setLoginEmail(e.target.value);
        setLoginError(prevErrors => ({ ...prevErrors, loginEmail: e.target.value ? '' : 'Email is required' }));
    };

    const handleLoginPasswordChange = (e) => {
        setLoginPassword(e.target.value);
        setLoginError(prevErrors => ({ ...prevErrors, loginPassword: e.target.value ? '' : 'Password is required' }));
    };

    const handleLoginSubmit = async (e) => {
        e.preventDefault();
        if (!loginEmail || !loginPassword) {
            setLoginError(prevErrors => ({
                ...prevErrors,
                loginEmail: !loginEmail ? 'Email is required' : '',
                loginPassword: !loginPassword ? 'Password is required' : '',
            }));
            return;
        }

        setLoading(true);
        try {
            const response = await axios.post('http://localhost:5001/api/users/login', { email: loginEmail, password: loginPassword });
            console.log('Login successful:', response.data);

            if (response.data.token) {
                console.log('Token received:', response.data.token);
                localStorage.setItem("token", response.data.token);
                console.log('Token stored in localStorage:', localStorage.getItem('token'));
                window.location.href = '/';
            } else {
                setLoginError(prevErrors => ({ ...prevErrors, general: 'No token received from server.' }));
            }
        } catch (error) {
            console.log('Error during login:', error);
            setLoginError(prevErrors => ({ ...prevErrors, general: `Login failed: ${error.response?.data?.message || 'Please try again.'}` }));
        } finally {
            setLoading(false);
        }
    };

    return (
        <div>
            <form className="login-sheet" onSubmit={handleLoginSubmit}>
                <label>
                    Email:
                    <input type="text" value={loginEmail} onChange={handleLoginEmailChange} aria-invalid={loginError.loginEmail ? "true" : "false"} aria-describedby="loginEmailError" />
                    {loginError.loginEmail && <p id="loginEmailError" className="error">{loginError.loginEmail}</p>}
                </label>
                <label>
                    Password:
                    <input type="password" value={loginPassword} onChange={handleLoginPasswordChange} aria-invalid={loginError.loginPassword ? "true" : "false"} aria-describedby="loginPasswordError" />
                    {loginError.loginPassword && <p id="loginPasswordError" className="error">{loginError.loginPassword}</p>}
                </label>
                <button type="submit" disabled={loading}>{loading ? 'Submitting...' : 'Submit'}</button>
                {loginError.general && <p className="error">{loginError.general}</p>}
            </form>
        </div>
    );
}

export default Login;

import { useState, useEffect } from "react";
import axios from "axios";

function Cart() {
    const [cart, setCart] = useState([]);
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        const fetchCart = async () => {
            setLoading(true);
            try {
                const token = localStorage.getItem('token');
                const config = { headers: { 'Authorization': `Bearer ${token}` } };
                const response = await axios.get('http://localhost:5001/api/cart', config);
                setCart(response.data.items);
            } catch (error) {
                setError('Error fetching cart');
            } finally {
                setLoading(false);
            }
        };
        fetchCart();
    }, []);

    const handleAddItem = async (productId, quantity) => {
        try {
            const token = localStorage.getItem('token');
            const config = { headers: { 'Authorization': `Bearer ${token}` } };
            await axios.post('http://localhost:5001/api/cart/add', { productId, quantity }, config);
            const response = await axios.get('http://localhost:5001/api/cart', config);
            setCart(response.data.items);
        } catch (error) {
            setError('Error adding item');
        }
    };

    const handleRemoveItem = async (productId) => {
        try {
            const token = localStorage.getItem('token');
            const config = { headers: { 'Authorization': `Bearer ${token}` } };
            await axios.delete(`http://localhost:5001/api/cart/remove/${productId}`, config);
            const response = await axios.get('http://localhost:5001/api/cart', config);
            setCart(response.data.items);
        } catch (error) {
            setError('Error removing item');
        }
    };

    return (
        <div>
            <h1>Shopping Cart</h1>
            {loading && <p>Loading...</p>}
            {error && <p className="error">{error}</p>}
            <ul>
                {cart.map(item => (
                    <li key={item.productId._id}>
                        <h2>{item.productId.name}</h2>
                        <p>Quantity: {item.quantity}</p>
                        <button onClick={() => handleRemoveItem(item.productId._id)}>Remove</button>
                    </li>
                ))}
            </ul>
        </div>
    );
}

export default Cart;

const mongoose = require('mongoose');

const cartSchema = new mongoose.Schema({
    userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
    items: [
        {
            productId: { type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: true },
            quantity: { type: Number, required: true, min: 1 },
        }
    ]
});

const Cart = mongoose.model('Cart', cartSchema);

module.exports = Cart;

const jwt = require('jsonwebtoken');

function auth(req, res, next) {
    const token = req.header('Authorization')?.replace('Bearer ', '');
    console.log('Received Token:', token);

    if (!token) {
        return res.status(401).json({ message: 'No token, authorization denied' });
    }

    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        req.user = { userId: decoded.userId, role: decoded.role };
        next();
    } catch (err) {
        res.status(401).json({ message: 'Token is not valid' });
    }
}

module.exports = auth;

import { findOne } from "../models/User";

// User login
router.post('/login', async (req, res) => {
    const { email, password } = req.body;

    try {
        const user = await findOne({ email });
        if (!user) {
            return res.status(400).json({ message: 'Invalid credentials' });
        }

        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) {
            return res.status(400).json({ message: 'Invalid credentials' });
        }

        const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });
        res.json({ token });
    } catch (err) {
        res.status(500).json({ message: err.message });
    }
});

Ive been researching this problem for hours and cant figure it out. the error pops up for all things i do on my website. When i signup login and access the shopping cart.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật