Created
June 7, 2019 11:25
-
-
Save brendaMan/12577cd1d2579223f9109e9423ca2d55 to your computer and use it in GitHub Desktop.
Express 4 - PUT 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 a 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