Node.js can be used to serve a vast range of purposes: you can build a command line tool, a proxy, a web server, and in its simplest form can be used just for querying a remote API and returning the output to the user. Almost everything today is available behind an API: weather forecasts, geolocation services and so on. The answer is simple: as a JavaScript developer you will interact every day with remote APIs and webservers. Making HTTP requests with Node.js: why?Īt this point you might be asking "Why would I ever do an HTTP request?". In the following post we'll use async/await, introduced in Node 7.6.0. Also, make sure to have one of the latest versions of Node.js. To follow along you should have a basic understanding of JavaScript and ES6. How to make HTTP requests in Node.js with various modules.I will focus mostly on GET requests in order to keep things simple and understandable. Starting from the easier one we will explore the "classic way" for doing HTTP requests all the way through libraries which support Promises. It could be an API, a website, or something else: at some point you will need some code to get meaningful data from one of those remote sources. Thanks to James Snell for sharing the Promise.race-based timeout pattern in his article Using AbortSignal in Node.js.HTTP requests are a means for fetching data from a remote source. You can view the full code which we’ve put together in this example on GitHub. Promise.race() will reject with that error. If the HTTP request does not complete in under 100 milliseconds, the timeout() function will abort the HTTP request and throw an error which explains that the request was aborted.If an error occurs when making the HTTP request, the promise returned by Promise.race() will reject with that error. The timeout created by timeout() will also be aborted. If the HTTP request made by makeRequest() completes in under 100 milliseconds - as specified by the argument to our timeout() function - the value of result will be the parsed JSON response body.With the functions that we’re calling in the array, that means: Our call to Promise.race() returns a promise that fulfills or rejects as soon as one of the promises in the array fulfills or rejects, with the value or reason from that promise. In the code snippet above we’re using the free fake API provided by JSON Placeholder. We don’t need to do anything with that error, but we do need to return so that the function doesn’t continue to execute and throw our "request aborted" error.Īfter defining our makeRequest() and timeout() functions, we pull it all together with Promise.race(): // example-node-fetch.mjsĬonst result = await Promise.race() We’ve wrapped the setTimeout() call in a try / catch block because if the cancelTimeout signal is aborted, the promise returned by setTimeout() rejects with an AbortError. We then throw an error with an error message which explains that the request was aborted. If the timeout completes without being aborted, we call the abort() method on our cancelRequest controller. We do this in the makeRequest() function above after our HTTP request has completed. This allows us to cancel the scheduled timeout by calling the cancelTimeout.abort() method. We’re passing the signal option here, with the AbortSignal in our cancelRequest abort controller. In this case it’s undefined as we don’t need a value here – we’re using setTimeout() to delay the execution of the code which comes after it. The value with which to fulfill the promise.The number of milliseconds to wait before fulfilling the promise.The promise variant of setTimeout() which we’re using here works quite differently to its better known callback based counterpart. Cancelling an HTTP request with an AbortSignal You can learn about support for the Abort API in different versions of Node.js in my article ‘ Cancel async operations with AbortController‘. If you’re using Node.js v14.x or an earlier version of Node.js you’ll probably want to use the abort-controller library (the Node.js core implementation was closely modelled on this library). It was backported to Node.js v14.17.0, but with an Experimental status. Node.js has had Stable support for the Abort API since v15.4.0, released in December 2020. Microsoft Edge 16 was the first browser to implement the Abort API in October 2017, but now all major browsers support it. The Abort API originated in the Web Platform. If you’re using a library or method which accepts an AbortSignal instance as an option, it will attach it’s own event handler for the abort event. In the example above we’ve registered one handler for the abort event type, which logs a message to let us know that the abort signal was triggered. It also dispatches an abort event from the AbortSignal instance in controller.signal to the list of registered handlers. When the controller.abort() method is called, it sets the signal’s aborted property to true.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |