Facebook
From NTN, 11 Months ago, written in JavaScript.
Embed
Download Paste or View Raw
Hits: 308
  1. // index.js
  2. const express = require('express');
  3. const bodyParser = require('body-parser');
  4. const mysql = require('mysql2');
  5.  
  6. const app = express();
  7. const port = 3000;
  8.  
  9. // Middleware to parse JSON bodies
  10. app.use(bodyParser.json());
  11.  
  12. // Create a connection to the database
  13. const db = mysql.createConnection({
  14.   host: 'localhost',
  15.   user: 'root', // replace with your MySQL username
  16.   password: '', // replace with your MySQL password
  17.   database: 'myapp',
  18. });
  19.  
  20. // Connect to the database
  21. db.connect((err) => {
  22.   if (err) {
  23.     console.error('Error connecting to the database:', err);
  24.     return;
  25.   }
  26.   console.log('Connected to the MySQL database.');
  27. });
  28.  
  29. // Login route
  30. app.post('/login', (req, res) => {
  31.   const { username, password } = req.body;
  32.  
  33.   if (!username || !password) {
  34.     return res.status(400).json({ message: 'Username and password are required' });
  35.   }
  36.  
  37.   const query = 'SELECT * FROM users WHERE username = ? AND password = ?';
  38.   db.query(query, [username, password], (err, results) => {
  39.     if (err) {
  40.       console.error('Error executing query:', err);
  41.       return res.status(500).json({ message: 'Internal server error' });
  42.     }
  43.  
  44.     if (results.length > 0) {
  45.       res.status(200).json({ message: 'Login successful', user: { username: results[0].username } });
  46.     } else {
  47.       res.status(401).json({ message: 'Invalid username or password' });
  48.     }
  49.   });
  50. });
  51.  
  52. app.listen(port, () => {
  53.   console.log(`Server running at http://localhost:${port}`);
  54. });
  55.