How to do it...

Let's perform the following steps to create an API status endpoint for our Express application:

  1. First, let's create a new route for all our API requests. Create a new file called /routes/api.js; inside this file, we will define two new routes:
var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
res.send('API is running');
});

router.get('/:param', function(req, res, next) {
var params = req.params;
var query = req.query;
Object.assign(params, query);
res.json(params);
});

module.exports = router;
  1. Next, we will update our /app.js configuration to import this new route, and provide it to Express as middleware using the use command:
...
var api = require('./routes/api');
var app = express();

...
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api', api);
...
  1. Finally, we must restart our Express server. Now, when we visit localhost:3000/api, we will see the API is running text; if we visit localhost:3000/api/foobar?search=barfoo, we will see a JSON response:
{
"param":"foobar",
"search":"barfoo"
}
It's important to note that unlike Angular-CLI, Express doesn't automatically reload changes to its configuration. You will need to manually restart the server every time you make a change to its configuration. In Chapter 9, Build Systems and Optimizations, we will cover how to add automatic live-reload to our Express web server.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.113.199