-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
43 lines (42 loc) · 1.87 KB
/
server.js
File metadata and controls
43 lines (42 loc) · 1.87 KB
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
//server.js
‘use strict’
//first we import our dependencies…
var express = require(‘express’);
var mongoose = require(‘mongoose’);
var bodyParser = require(‘body-parser’);
var Comment = require(‘./model/comments’);
//and create our instances
var app = express();
var router = express.Router();
//set our port to either a predetermined port number if you have set
//it up, or 3001
var port = process.env.API_PORT || 3001;
//db config
//Integrating the database MongoDB from Amazon AWS using MLab( database as a service provider) using a driver via
// the Standard MongoDB URI
mongoose.connect('mongodb://darkJedi:mongorun121@ds111940.mlab.com:11940/merncommentbox')
//now we should configure the API to use bodyParser and look for
//JSON data in the request body
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//To prevent errors from Cross Origin Resource Sharing, we will set
//our headers to allow CORS with middleware like so:
app.use(function(req, res, next) {
res.setHeader(‘Access-Control-Allow-Origin’, ‘*’);
res.setHeader(‘Access-Control-Allow-Credentials’, ‘true’);
res.setHeader(‘Access-Control-Allow-Methods’, ‘GET,HEAD,OPTIONS,POST,PUT,DELETE’);
res.setHeader(‘Access-Control-Allow-Headers’, ‘Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers’);
//and remove cacheing so we get the most recent comments
res.setHeader(‘Cache-Control’, ‘no-cache’);
next();
});
//now we can set the route path & initialize the API
router.get(‘/’, function(req, res) {
res.json({ message: ‘API Initialized!’});
});
//Use our router configuration when we call /api
app.use(‘/api’, router);
//starts the server and listens for requests
app.listen(port, function() {
console.log(`api running on port ${port}`);
});