Full-Stack Web Development with Vue.js and Node

(singke) #1
Building the Real Application Chapter 5

Since these controllers have the routes, we need to include these files in our main entry
point as well. For our backend, the main entry file is server.js. So, let's add the following


highlighted code block in server.js:


//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);
});

// Include controllers
fs.readdirSync("controllers").forEach(function (file) {
if(file.substr(-3) == ".js") {
const route = require("./controllers/" + file)
route.controller(app)
}
})

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

This code block will include all our controllers' files and we don't have to add each of them
manually.


Connecting frontend and backend


Now, we have the model and an endpoint. The next thing to do is to call this endpoint


when we hit the Submit button in AddMovie.vue.


This is the part where we need to communicate the frontend and the backend. For this, we


need to use a separate package called axios.


The axios package helps us to make the HTTP requests from the Node.js. It helps to make


the Ajax calls from the frontend. There are several alternatives for axios as well, such as
fetch, and superagent. But axios has been successful enough to become the most popular


among these. So we will be using the same as well.

Free download pdf