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.