i am using vite react,
From frontend which is running on localhost:3000, if i make a api call to backend which on localhost:5000, frontend always make a api call at port 3000 insted of 5000.enter image description here
below is how my code looks
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
server: {
port: 3000, // Frontend runs on port 3000
proxy: {
'/api': {
target: 'http://localhost:5000/', // Backend running on port 5000
changeOrigin: true,
secure: false,
},
},
},
});
Login.jsx
const LoginAdmin = () => {
const formik = useFormik({
initialValues: {
email: '',
password: '',
},
validationSchema: Yup.object({
email: Yup.string().email('Invalid email address').required('Email is required'),
password: Yup.string().required('Password is required'),
}),
onSubmit: async (values) => {
try {
const response = await axios.post('/api/admin/login', values);
alert('Login successful!');
console.log(response.data);
localStorage.setItem('token', response.data.token);
} catch (error) {
console.error('Login error:', error);
alert('Invalid credentials or account not active/approved.');
}
},
});
return ()
};
server.js
const app = express();
// Middleware
app.use(cors({
origin: 'http://localhost:3000', // Allow requests from frontend
credentials: true, // Allow sending cookies or authentication tokens
}));
app.use(express.json());
// Connect to MongoDB
connectDB();
// Use admin routes
app.use('/api/admin', adminRoutes);
// Basic route
app.get('/', (req, res) => {
res.send('Hello from the ES6 backend, DB connected');
});
// Start server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
i checked form and Axios request are set up correctly.
also Ensured the backend endpoint exists and is correctly handling the request.
also Verified the proxy configuration in vite.config.js.
thinking it may be some silly error, even restart servers and system.