Full-Stack Web Development with Vue.js and Node

(singke) #1
Building the Real Application Chapter 5

The next part is to create the necessary endpoints and models so that we can add the
movies to the database.


To do that, we first need to install the required packages:


body-parser: To parse the incoming requests
cors: To handle cross-origin requests between frontend and backend
morgan: HTTP request logger
mongoose: Object modeling for MongoDB

Let's install all of these packages by running the following command in the Terminal:


$ npm install morgan body-parser cors mongoose --save

Adding a server file

Now, we need to set up the server for our application. Let's add a file called server.js in


the root of the application and add the following content:


const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const morgan = require('morgan');
const fs = require('fs');

const app = express();
const router = express.Router();
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(cors());

//connect to mongodb
mongoose.connect('mongodb://localhost/movie_rating_app', function() {
console.log('Connection has been made');
})
.catch(err => {
console.error('App starting error:', err.stack);
process.exit(1);
});

router.get('/', function(req, res) {
res.json({ message: 'API Initialized!'});
});
Free download pdf