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.
In the /js
directory, create a new file named request.js
Move the request()
function definition from app.js
into request.js
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);
});
};
In app.js
, import the request
module to make the request function available
import request from './request';
Build the app:
npm run webpack
Make sure your local http server is started, open a browser and access http://localhost:8080.
The final code for this step is available in this branch.