Commit c7dd5c0c authored by Tharaka it19975696's avatar Tharaka it19975696 🎧

MySQL connection and API service

parent a08e1767
//Mongo
DB_USERNAME=R24-152 DB_USERNAME=R24-152
DB_PASSWORD=1234!@#$Qw DB_PASSWORD=1234!@#$Qw
\ No newline at end of file
//MySQL
...@@ -13,9 +13,11 @@ ...@@ -13,9 +13,11 @@
"@testing-library/react": "^13.4.0", "@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0", "@testing-library/user-event": "^13.5.0",
"axios": "^1.6.8", "axios": "^1.6.8",
"cors": "^2.8.5",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.19.2", "express": "^4.19.2",
"mongoose": "^8.3.1", "mongoose": "^8.3.1",
"mysql": "^2.18.1",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-router-dom": "^6.22.3", "react-router-dom": "^6.22.3",
...@@ -6179,6 +6181,14 @@ ...@@ -6179,6 +6181,14 @@
"node": "*" "node": "*"
} }
}, },
"node_modules/bignumber.js": {
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz",
"integrity": "sha512-t/OYhhJ2SD+YGBQcjY8GzzDHEk9f3nerxjtfa6tlMXfe7frs/WozhvCNoGvpM0P3bNf3Gq5ZRMlGr5f3r4/N8A==",
"engines": {
"node": "*"
}
},
"node_modules/binary-extensions": { "node_modules/binary-extensions": {
"version": "2.2.0", "version": "2.2.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz",
...@@ -6790,6 +6800,18 @@ ...@@ -6790,6 +6800,18 @@
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="
}, },
"node_modules/cors": {
"version": "2.8.5",
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
"integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",
"dependencies": {
"object-assign": "^4",
"vary": "^1"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/cosmiconfig": { "node_modules/cosmiconfig": {
"version": "7.1.0", "version": "7.1.0",
"resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.1.0.tgz", "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.1.0.tgz",
...@@ -13383,6 +13405,52 @@ ...@@ -13383,6 +13405,52 @@
"multicast-dns": "cli.js" "multicast-dns": "cli.js"
} }
}, },
"node_modules/mysql": {
"version": "2.18.1",
"resolved": "https://registry.npmjs.org/mysql/-/mysql-2.18.1.tgz",
"integrity": "sha512-Bca+gk2YWmqp2Uf6k5NFEurwY/0td0cpebAucFpY/3jhrwrVGuxU2uQFCHjU19SJfje0yQvi+rVWdq78hR5lig==",
"dependencies": {
"bignumber.js": "9.0.0",
"readable-stream": "2.3.7",
"safe-buffer": "5.1.2",
"sqlstring": "2.3.1"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mysql/node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="
},
"node_modules/mysql/node_modules/readable-stream": {
"version": "2.3.7",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz",
"integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==",
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"node_modules/mysql/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/mysql/node_modules/string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
"dependencies": {
"safe-buffer": "~5.1.0"
}
},
"node_modules/mz": { "node_modules/mz": {
"version": "2.7.0", "version": "2.7.0",
"resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz",
...@@ -16778,6 +16846,14 @@ ...@@ -16778,6 +16846,14 @@
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
"integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==" "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g=="
}, },
"node_modules/sqlstring": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz",
"integrity": "sha512-ooAzh/7dxIG5+uDik1z/Rd1vli0+38izZhGzSa34FwR7IbelPWCCKSNIl8jlL/F7ERvy8CB2jNeM1E9i9mXMAQ==",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/stable": { "node_modules/stable": {
"version": "0.1.8", "version": "0.1.8",
"resolved": "https://registry.npmjs.org/stable/-/stable-0.1.8.tgz", "resolved": "https://registry.npmjs.org/stable/-/stable-0.1.8.tgz",
......
// server/index.js
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
app.use(cors());
app.use(express.json());
const db = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME
});
app.get('/', (req, res) => {
res.json({ message: 'Welcome to the server API!' });
});
app.get('/test-db', (req, res) => {
db.query('SELECT 1 + 1 AS solution', (err, results) => {
if (err) {
return res.status(500).send(err.toString());
}
res.status(200).json({ solution: results[0].solution });
});
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
// api.js
import axios from 'axios';
const API_BASE_URL = 'http://localhost:5000'; // Use your actual backend URL here
export const testDbConnection = async () => {
try {
const response = await axios.get(`${API_BASE_URL}/test-db`);
return response.data;
} catch (error) {
throw error;
}
};
// src/App.js // src/App.js
import React, { useState } from 'react'; import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'; import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import Home from './Home'; import Home from './Home';
import About from './About'; import About from './About';
import Insights from './Insights'; import Insights from './Insights';
import Navbar from './Navbar'; import Navbar from './Navbar';
import LoginPage from './LoginPage'; import LoginPage from './LoginPage';
import { testDbConnection } from '../api/api';
function App() { function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false); const [isLoggedIn, setIsLoggedIn] = useState(false);
const [dbTestResult, setDbTestResult] = useState(null);
const handleLoginSuccess = () => { const handleLoginSuccess = () => {
setIsLoggedIn(true); setIsLoggedIn(true);
}; };
const handleTestDbConnection = async () => {
try {
const response = await testDbConnection();
setDbTestResult(response);
console.log(response);
} catch (error) {
console.error('Database test failed:', error);
setDbTestResult(null);
}
};
// Test the database connection once when the app is loaded
useEffect(() => {
handleTestDbConnection();
}, []);
return ( return (
<Router> <Router>
<Navbar /> <Navbar />
...@@ -23,7 +41,7 @@ function App() { ...@@ -23,7 +41,7 @@ function App() {
<> <>
<Route path="/about" element={<About />} /> <Route path="/about" element={<About />} />
<Route path="/insights" element={<Insights />} /> <Route path="/insights" element={<Insights />} />
<Route path="/" element={<Home />} /> <Route path="/" element={<Home onTestDbConnection={handleTestDbConnection} dbTestResult={dbTestResult} />} />
</> </>
) : ( ) : (
// If not logged in, redirect to login page // If not logged in, redirect to login page
......
import React from 'react'; import React from 'react';
import ReactDOM from 'react-dom/client'; import ReactDOM from 'react-dom/client';
import './index.css'; import './index.css';
import App from './App'; import App from './components/App';
import reportWebVitals from './reportWebVitals'; import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root')); const root = ReactDOM.createRoot(document.getElementById('root'));
...@@ -11,6 +11,7 @@ root.render( ...@@ -11,6 +11,7 @@ root.render(
</React.StrictMode> </React.StrictMode>
); );
// If you want to start measuring performance in your app, pass a function // If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log)) // to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
......
require('dotenv').config(); // Make sure to require dotenv as early as possible
const express = require('express');
const mongoose = require('mongoose');
const app = express();
// Use JSON middleware to parse JSON bodies into JS objects
app.use(express.json());
// Connect to MongoDB
const username = encodeURIComponent(process.env.DB_USERNAME);
const password = encodeURIComponent(process.env.DB_PASSWORD);
const dbCluster = process.env.DB_CLUSTER;
const dbURI = `mongodb+srv://${username}:${password}@${dbCluster}/myDatabaseName?retryWrites=true&w=majority`;
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.error('Connection error:', err));
// Define routes for your API
app.get('/', (req, res) => {
res.send('Hello World!');
});
// Example POST route
app.post('/login', (req, res) => {
// This is an example, you would have actual logic to verify credentials
const { username, password } = req.body;
if (username === 'teacher' && password === '1234') {
res.json({ status: 'ok', message: 'Teacher logged in' });
} else if (username === 'student' && password === '1234') {
res.json({ status: 'ok', message: 'Student logged in' });
} else {
res.status(401).json({ status: 'error', message: 'Invalid credentials' });
}
});
// Start the server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment