-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
69 lines (57 loc) · 1.88 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const environment = process.env.NODE_ENV || 'development';
const configuration = require('./knexfile')[environment];
const database = require('knex')(configuration);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('port', process.env.PORT || 3000);
app.locals.title = 'Advice Slips';
app.use(function (request, response, next) {
response.header("Access-Control-Allow-Origin",
"*");
response.header("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept");
response.header("Access-Control-Allow-Methods",
"GET, POST, PATCH, DELETE, OPTIONS");
next();
});
app.use(function (request, response, next) {
response.header("Access-Control-Allow-Origin",
"*");
response.header("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept");
response.header("Access-Control-Allow-Methods",
"GET, POST, PATCH, DELETE, OPTIONS");
next();
});
app.get('/', (request, response) => {
response.send('To contribute advice to this API visit https://mnhollandplum.github.io/magic_8_ball/');
});
//get all slips of advice
app.get('/api/v1/slips', (request, response) => {
database('slips').select()
.then((slips) => {
response.status(200).json(slips);
})
.catch((error) => {
response.status(500).json({ error });
});
});
//post a new advice slip
app.post('/api/v1/slips', (request, response) => {
const slip = request.body;
console.log(slip)
database('slips').insert(slip, 'id')
.then(slip => {
response.status(201).json({ "slip": request.body })
})
.catch(error => {
response.status(500).json({ error });
});
});
app.listen(app.get('port'), () => {
console.log(`${app.locals.title} is running on ${app.get('port')}.`);
});
module.exports = app