CRUD API with MySQL
index.js:
const express=require('express');
const con=require('./config12')
const app=express();
app.use(express.json());
app.get("/", (req, resp)=>{
con.query("select * from user", (err, result)=>{
if(err){
resp.send("error")
}else{
resp.send(result)
}
})
});
app.post('/', (req, resp)=>{
const data=req.body;
con.query('Insert into users3 SET?', data,(error, result, fields)=>{
if(error) error;
resp.send(result)
})
});
app.put('/:id', (req, resp)=>{
const data=[req.body.name, req.body.password, req.params.id];
con.query("Update users SET name=?, password=? where id =? ", data, (err, result, fields)=>{
if(err) throw error;
resp.send(result)
})
});
app.delete('/:id', (req, resp)=>{
con.query("Delete from users3 WHERE id="+req.params.id, (error, result)=>{
if(error) throw error;
resp.send(result)
})
})
app.listen(5000)
config.js:
const mysql=require('mysql')
const con=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'test'
});
con.connect((err)=>{
if(err){
console.warn("error in connection");
}
})
module.exports=con;
Comments
Post a Comment