const express = require('express');
const app = express();
const port = 3000;
const mysql = require('mysql2');
app.use(express.json())
const connection = mysql.createConnection({
host : '127.0.0.1',
port : '3307',
user : 'root',
password : '1234',
database : 'nodejs'
});
app.get('/', (req, res) => {
res.end('hello express');
});
app.get('/:id', (req, res) => {
const id = req.params.id;
const query = `select * from products where id = ${id}`;
console.log(query);
connection.execute(query, (err, results, fiedls) => {
if(err) throw err;
const result = {
status: 200,
results,
}
//results.forEach(product => console.log(product.id, product.name));
const json = JSON.stringify(result);
res.send(json);
});
});
app.post('/products', (req, res) => {
let body = req.body;
const query = `insert products (name, category, price) values ('${body.name}', '${body.category}', '${body.price}')`;
console.log(query);
connection.execute(query, (err, results, fiedls) => {
if(err) throw err;
const result = {
status: 200,
}
const json = JSON.stringify(result);
res.send(json);
});
});
app.delete('/products', (req, res) => {
let body = req.body;
const query = `DELETE FROM products WHERE id = '${body.id}'`;
console.log(query);
connection.execute(query, (err, results, fiedls) => {
if(err) throw err;
const result = {
status: 200,
}
const json = JSON.stringify(result);
res.send(json);
});
});
app.put('/products', (req, res) => {
let body = req.body;
const query = `UPDATE products SET name = '${body.name}', category = '${body.category}', price = '${body.price}' WHERE id = '${body.id}'`;
console.log(query);
connection.execute(query, (err, results, fiedls) => {
if(err) throw err;
const result = {
status: 200,
}
const json = JSON.stringify(result);
res.send(json);
});
});
app.get('/dbconnect', (req, res) => {
console.log('conncetion :' + connection);
res.end('connectioin test');
});
app.listen(port, () => {
console.log(`server is running at ${port} port.`);
});