I’m using Vite with React/Express and started the app with npm run dev – running on http://localhost:5173 and using http://localhost:5000 for the backend in the meantime. When trying to test a post request using fetch(), I’m constantly getting the following error:
server/App.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const userRoutes = require('./routes/user-routes');
const HttpError = require('./models/http-error');
const app = express();
app.use(bodyParser.json());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
next();
})
app.use('/user', userRoutes);
app.use((req, res, next) => {
const error = new HttpError('Could not find this route', 404);
next(error);
});
app.use((error, req, res, next) => {
if (res.headersSent) {
return next(error);
}
res.status(error.code || 500);
res.json({ message: error.message || 'An unknown error occurred' });
});
mongoose
.connect('mongodb+srv://<username>:<password>@ts-trainings.ic7mcip.mongodb.net/user?retryWrites=true&w=majority&appName=ts-trainings')
.then(() => {
app.listen(5000, () => {
console.log('Server is running on port 5000');
console.log('Connection Success');
});
})
.catch(err => {
console.log('Connection Failed');
console.log(err);
});
user-routes.js:
const express = require("express");
const { check } = require("express-validator");
const userController = require("../controllers/user-controllers");
const router = express.Router();
router.get("/", userController.getUser);
router.post(
"/signup",
[
check("firstname").not().isEmpty(),
check("lastname").not().isEmpty(),
check("email").normalizeEmail().isEmail(),
check("username").not().isEmpty(),
check("password").isLength({ min: 6 }),
],
userController.signup
);
router.post("/login", userController.login);
module.exports = router;
user-controllers.js:
const login = async (req, res, next) => {
const { username, password } = req.body;
let existingUser;
try {
existingUser = await User.findOne({ username: username });
} catch (err) {
const error = new HttpError("Login failed, please contact support", 500);
return next(error);
}
if (!existingUser || existingUser.password !== password) {
const error = new HttpError(
'Invalid credentials, could not log you in.',
401
);
return next(error);
}
res.json({ message: "Logged In" });
};
Frontend page:
import React, { useState } from 'react';
import { Button, Col, Form, InputGroup, Row, Alert } from 'react-bootstrap';
import '../assets/css/AdminLogin.css';
const AdminLogin = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [validated, setValidated] = useState(false);
const [alert, setAlert] = useState({ show: false, message: '', variant: '' });
const handleLogin = async (event) => {
const form = event.currentTarget;
event.preventDefault();
if (form.checkValidity() === false) {
event.stopPropagation();
setValidated(true);
return;
}
try {
const response = await fetch('http://localhost:5000/user/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
});
const result = await response.json();
if (result.success) {
setAlert({ show: true, message: 'Login successful!', variant: 'success' });
// Redirect to a new page or take any other action
} else {
setAlert({ show: true, message: 'Invalid credentials. Please try again.', variant: 'danger' });
}
} catch (error) {
setAlert({ show: true, message: 'An error occurred. Please try again later.', variant: 'danger' });
}
};
return (
<Form noValidate validated={validated} onSubmit={handleLogin} className="loginForm">
<Row className="mb-2">
<Form.Group as={Col} md="6">
<Form.Label>Username</Form.Label>
<InputGroup hasValidation>
<InputGroup.Text id="inputGroupPrepend">@</InputGroup.Text>
<Form.Control
type="text"
placeholder="Username"
aria-describedby="inputGroupPrepend"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
<Form.Control.Feedback type="invalid">
Enter a username
</Form.Control.Feedback>
</InputGroup>
</Form.Group>
<Form.Group as={Col} md="6" controlId="validationCustom01">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
<Form.Control.Feedback type="invalid">
Enter a password
</Form.Control.Feedback>
</Form.Group>
</Row>
{alert.show && (
<Alert variant={alert.variant} onClose={() => setAlert({ show: false })} dismissible>
{alert.message}
</Alert>
)}
<div className='buttonContainer'>
<Row>
<Col className="text-center">
<Button className="mainButton mt-3" variant="outline-info" size="lg" href="/register">
Register Instead
</Button>
</Col>
<Col className="text-center">
<Button className="mainButton mt-3" type="submit" variant="outline-warning" size="lg">{' '}
Login
</Button>
</Col>
</Row>
</div>
</Form>
);
};
export default AdminLogin;
Any guidance would be appreciated.