concept request in category angular

This is an excerpt from Manning's book Getting MEAN with Mongo, Express, Angular, and Node.js 2ED.
A Node.js server is single-threaded and works differently from a multithreaded server. Rather than giving each visitor a unique thread and a separate silo of resources, the server has every visitor join the same thread. A visitor and thread interact only when necessary—when the visitor is requesting something or the thread is responding to a request.
The basic construct for making a request is simple, being a single command taking parameters for options and a callback like this:
![]()
The options specify everything for the request, including the URL, request method, request body, and query string parameters. These options, indeed, are the ones you’ll be using in this chapter, and they’re detailed in table 7.1.
Table 7.1. Four common request options for defining a call to an API
Description
Required
url Full URL of the request to be made, including protocol, domain, path, and URL parameters Yes method Method of the request, such as GET, POST, PUT, or DELETE No—defaults to GET if not specified json Body of the request as a JavaScript object; an empty object should be sent if no body data is needed Yes—ensures that the response body is also parsed as JSON qs JavaScript object representing any query string parameters No
One of the main reasons for catching errors is to make sure that they don’t cause code to fail. The first point of weakness is in the request callback, where you’re manipulating the response before sending the data off to be rendered. This is fine if the data is always consistent, but you don’t have that luxury.
The request callback currently runs a for loop to format the distances no matter what data is returned by the API. You should run this loop only when the API returns a 200 code and some results.
Listing 7.9. Validating that the API has returned some data before trying to use it
request( requestOptions, (err, {statusCode}, body) => #1 let data = []; if (statusCode === 200 && body.length) { #2 data = body.map( (item) => { item.distance = formatDistance(item.distance): return item; }); } renderHomepage(req, res, data); } );

This is an excerpt from Manning's book Getting MEAN with Mongo, Express, Angular, and Node Livebook.
Our Express application needs to be able to call the API URLs that we set up in chapter 6—sending the correct request method, of course—and then be able to interpret the response. To help with doing this we’ll use a module called request.