Advertisement
agung_py

Untitled

Feb 14th, 2024
867
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 2.15 KB | Source Code | 0 0
  1. const express = require('express');
  2. const mysql = require('mysql');
  3. const cors = require('cors');
  4. const bodyParser = require('body-parser');
  5.  
  6. const app = express();
  7. const port = 3000;
  8.  
  9. app.use(cors());
  10. app.use(bodyParser.urlencoded({ extended: true }));
  11. app.use(bodyParser.json());
  12.  
  13. const db = mysql.createConnection({
  14.   host: 'localhost',
  15.   user: 'root',
  16.   password: '',
  17.   database: 'scan_barcode',
  18. });
  19.  
  20. db.connect((err) => {
  21.   if (err) {
  22.     console.log('Error connecting to MySQL:', err);
  23.   } else {
  24.     console.log('Connected to MySQL');
  25.   }
  26. });
  27.  
  28. app.post('/login', (req, res) => {
  29.   const username = req.body.username;
  30.   const password = req.body.password;
  31.  
  32.   const query = `INSERT INTO login (namauser, password) VALUES ('${username}', '${password}')`;
  33.  
  34.   db.query(query, (err, result) => {
  35.     if (err) {
  36.       console.log('Error executing query:', err);
  37.       res.status(500).send('Internal Server Error');
  38.     } else {
  39.       console.log('User inserted successfully');
  40.       res.status(200).send('User inserted successfully');
  41.     }
  42.   });
  43. });
  44.  
  45. // Get product by kodeBarang
  46. app.get('/master_barang/:kodeBarang', (req, res) => {
  47.   const kodeBarang = req.params.kodeBarang;
  48.   const sql = 'SELECT * FROM master_barang WHERE kodeBarang = ? LIMIT 1';
  49.   db.query(sql, kodeBarang, (err, result) => {
  50.     if (err) throw err;
  51.     if (result.length > 0) {
  52.       res.send(result[0]);
  53.     } else {
  54.       res.status(404).send('Product not found');
  55.     }
  56.   });
  57. });
  58.  
  59. // Add a new product
  60. app.post('/master_barang', (req, res) => {
  61.   const product = req.body;
  62.   const sql = 'INSERT INTO master_barang SET ?';
  63.   db.query(sql, product, (err, result) => {
  64.     if (err) throw err;
  65.     res.send('Product added');
  66.   });
  67. });
  68.  
  69. // Delete a product by kodeBarang
  70. app.delete('/master_barang/:kodeBarang', (req, res) => {
  71.   const kodeBarang = req.params.kodeBarang;
  72.   const sql = 'DELETE FROM master_barang WHERE qty = 0 AND kodeBarang = ?';
  73.   db.query(sql, kodeBarang, (err, result) => {
  74.     if (err) throw err;
  75.     res.send('Product deleted');
  76.   });
  77. });
  78.  
  79. app.listen(port, () => {
  80.   console.log(`Server is running on port ${port}`);
  81. });
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement