I am working on a workout website for practice and fun. I can enter a workout and it saves to mysql but when i try and fetch and show the workouts in the db im getting errors. In Postman i can see users but using http://localhost:3000/api/workouts Just shows a blank page.
http://localhost:3000/test-db This on the other hand works. I will attach my code, i cant see why
http://localhost:3000/api/workouts doesnt show workouts.
SELECT * FROM workouts in mysql does show the workouts.
It has to be something with my server.js, I want to be able to see the workouts on postman.
I cannot post images due to not having 10 rep.
const express = require('express');
const cors = require('cors');
const db = require('./src/config/db'); // Adjust the path as needed to your db config
require('dotenv').config();
const app = express();
app.use(express.json());
// app.use(cors());
app.use(cors({
origin: ['http://localhost:3000', 'http://localhost:3001'], // allow requests from these origins
methods: ['GET', 'POST'], // allow these HTTP methods
allowedHeaders: ['Content-Type', 'Authorization'], // allow these headers
}));
// Test endpoint to check database connection
app.get('/test-db', (req, res) => {
// Query the database to retrieve a list of tables
db.query('SHOW TABLES', (err, results) => {
if (err) {
console.error(err);
res.status(500).send('Database connection error');
} else {
// Return the list of tables as JSON response
res.status(200).json(results);
}
});
});
// Login endpoint for user authentication
app.post('/api/login', (req, res) => {
const { email, password } = req.body;
// Query database for user by email and password
const query = 'SELECT * FROM users WHERE email = ? AND password = ?';
db.query(query, [email, password], (err, results) => {
if (err) {
return res.status(500).json({ message: "Database error", error: err });
}
if (results.length === 0) {
return res.status(401).json({ message: "Invalid email or password" });
}
// Send success response if user is found
res.json({ message: "Login successful" });
});
});
// Signup endpoint for user registration
app.post('/api/signup', async (req, res) => {
const { email, password } = req.body;
try {
// Check if user already exists in the database
const existingUser = await db.query('SELECT * FROM users WHERE email = ?', [email]);
if (existingUser.length > 0) {
return res.status(400).json({ message: 'Email already exists' });
}
// Insert new user into the database
await db.query('INSERT INTO users (email, password) VALUES (?, ?)', [email, password]);
// Return success message if user is successfully registered
res.status(201).json({ message: 'User registered successfully' });
} catch (error) {
console.error('Error:', error);
res.status(500).json({ message: 'An error occurred. Please try again later.' });
}
});
// Endpoint to save workout data to the database
app.post('/api/workouts', async (req, res) => {
const { workout } = req.body;
try {
// Insert the workout data into the database without the workout_date field
await db.query('INSERT INTO workouts (workout_name, user_id) VALUES (?, ?)', [workout.workout_name, workout.user_id]);
// Return success message if workout is successfully saved
res.status(201).json({ message: 'Workout saved successfully' });
} catch (error) {
console.error('Error:', error);
res.status(500).json({ message: 'An error occurred. Please try again later.' });
}
});
// Endpoint to fetch all workouts from the database
app.get('/api/workouts', async (req, res) => {
try {
const workouts = await db.query('SELECT * FROM workouts');
console.log('Workouts:', workouts);
const workoutRows = workouts.rows;
res.status(200).json(workoutRows);
} catch (error) {
console.error('Error fetching workouts:', error);
res.status(500).json({ message: 'An error occurred. Please try again later.' });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
I have tried changing the server.js code but nothing seems to work.