Modularizing HTTP Requests

In this unit, you turn the request function into a module so you can easily use it in different parts of the application, or in different applications.

Steps

  1. In the /js directory, create a new file named request.js

  2. Move the request() function definition from app.js into request.js

  3. Export that function as the default function for the module.

    The request module should look like this:

    export default obj => {
        return new Promise((resolve, reject) => {
            let xhr = new XMLHttpRequest();
            xhr.open(obj.method || "GET", obj.url);
            if (obj.headers) {
                Object.keys(obj.headers).forEach(key => {
                    xhr.setRequestHeader(key, obj.headers[key]);
                });
            }
            xhr.onload = () => {
                if (xhr.status >= 200 && xhr.status < 300) {
                    resolve(xhr.response);
                } else {
                    reject(xhr.statusText);
                }
            };
            xhr.onerror = () => reject(xhr.statusText);
            xhr.send(obj.body);
        });
    };
    
  4. In app.js, import the request module to make the request function available

    import request from './request';
    
  5. Build the app:

     npm run webpack
    
  6. Make sure your local http server is started, open a browser and access http://localhost:8080.

Solution

The final code for this step is available in this branch.

comments powered by Disqus