Created
June 7, 2019 11:31
-
-
Save brendaMan/d23eff72ccd918b433f18cf7745c118d to your computer and use it in GitHub Desktop.
Express 5 - DELETE method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const app = express(); | |
const port = 3000; | |
const connection = require('./conf'); | |
const bodyParser = require('body-parser'); | |
app.use(bodyParser.json()); | |
//To support url-encoded bodies | |
app.use(bodyParser.urlencoded({ | |
extended: true | |
}) | |
); | |
app.get('/', (req, res) => { | |
res.send('Hi, this is Express') | |
}) | |
app.get('/api/movies', (req, res) => { | |
connection.query('SELECT * from movie', (err, results) => { | |
if (err) { | |
console.log(err) | |
res.status(500).send(err.message); | |
} else { | |
res.json(results); | |
} | |
}); | |
}); | |
app.get('/api/movies/name', (req, res) => { | |
connection.query('SELECT name from movie', (err, results) => { | |
if (err) { | |
res.status(500).send(err.message); | |
} else { | |
res.json(results); | |
} | |
}); | |
}); | |
app.post('/api/movies', (req, res) => { | |
// console.log("POST /api/movie", formData); | |
const formData = req.body; | |
connection.query('Insert into movie set ?', formData, (err, results) => { | |
if (err) { | |
console.log(err); | |
res.results(500).send('There is an error while saving a movie'); | |
} else { | |
res.sendStatus(200); | |
} | |
}); | |
}); | |
app.put('/api/movies/:id', (req, res) => { | |
const idMovie = req.params.id; | |
const formData = req.body; | |
connection.query('UPDATE movie SET ? WHERE id = ?', [formData, idMovie], err => { | |
if (err) { | |
console.log(err); | |
res.status(500).send("Error editing the movie"); | |
} else { | |
res.sendStatus(200); | |
} | |
}); | |
}); | |
app.delete('/api/movies/:id', (req, res) => { | |
const idMovie = req.params.id; | |
connection.query('DELETE FROM movie WHERE id = ?', [idMovie], err => { | |
if (err) { | |
console.log(err); | |
res.status(500).send('Error deleting the movie'); | |
} else { | |
res.sendStatus(200); | |
} | |
}); | |
}); | |
app.listen(port, (err) => { | |
if(err) { | |
throw new Error('There is an error!') | |
} | |
console.log(`Im listening on ${port}`) | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment