Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing REST APIs Chapter 4

Also, in controllers/users.js, we have the following:


module.exports.controller = (app) => {
// get homepage
app.get('/users', (req, res) => {
res.render('index', { title: 'Users' });
})
}

Adding a GET endpoint in the users controller

Let's add a route to our controllers/users.js that will fetch all the user's records from


the database.


Currently, with the code we have in our users controller, when we


visit http://localhost:3000/users, it only returns a title, Users. Let's modify this


code to incorporate a GET request to fetch all user requests.


Fetching all users

First, start the server with $ nodemon app.js. Now, in controllers/users.js:


var User = require("../models/User");

module.exports.controller = (app) => {
// get all users
app.get('/users', (req, res) => {
User.find({}, 'name email', function (error, users) {
if (error) { console.log(error); }
res.send(users);
})
})
}

Now that we have our code in place, let's test this endpoint using the Postman app. In the


Postman app, add the necessary details in the URL. When we hit the Send button, we
should see the response as follows:

Free download pdf