-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
54 lines (42 loc) · 1.46 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
var express = require('express');
var mysql = require('mysql');
var bodyParser = require('body-parser');
var app = express();
var password = require('./secrets.json').password;
var connection = mysql.createConnection({
host: '35.202.35.215',
user: 'root',
password: password,
database: 'data'
});
app.use(bodyParser.json());
app.get('/', function (req, res) {
res.send('Hello World');
});
app.get('/pet/:petId', function (request, response) {
connection.query('SELECT * FROM pets where id = ?;', [request.params.petId], function (error, results) {
if (error) {
console.log('Error:', error);
return response.status(500).send('Internal server error');
}
var petWithGivenPetId = results[0];
if (petWithGivenPetId) {
response.setHeader('Content-Type', 'application/json');
response.send(JSON.stringify(petWithGivenPetId));
}
else {
response.status(404) // HTTP status 404: NotFound
.send('Not found');
}
});
});
app.post('/pet', function(request, response) {
connection.query('INSERT INTO pets (name, type) VALUES (?,?);', [request.body.name, request.body.type], function (error, results) {
if (error) {
console.log('Error:', error);
return response.status(500).send('Internal server error');
}
response.status(201).send('resource created');
});
});
app.listen(8080);