How it works...

We only had to add a couple of lines, and everything was set up. We can see our code working by either changing our logger from the previous section, or by writing code like this:

// Source file: src/get_parameters.js

app.use("*", (req, res) => {
console.log(req.query, req.body);
res.send("Server alive, with Express!");
});

URL parameters are automatically separated by Express into req.query, and req.body will be parsed by bodyParser. We can try a couple of service calls, a GET and a POST, to cover all cases:

> curl "http://127.0.0.1:8080/birthdays?day=22&month=9&year=1960" 
> curl -X POST --data "name=FK" "http://127.0.0.1:8080/persons"

The output will be as follows:

> node out/get_parameters.js
Mini server (with Express) ready at http://localhost:8080/!
{ day: '22', month: '9', year: '1960' } {}
{} { name: 'FK' }

In the first case (GET), we can see that req.query is an object with the three query parameters, while in the second case (POST) there are no query parameters, but the req.body provides the single parameter (name) we provided.

This should convince you of the merits of Express' design, based on a middleware stack, but let's go through some more examples, such as working with static files, routing, security, and more.

..................Content has been hidden....................

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