theWhiteFox DESIGNING & BUILDING WEBSITE / MOBILE APPS

thewhitefox

Fetch API webpack

2021 November 20th Written by theWhiteFox

Why Fetch & Webpack?

Learning how to make HTTP requests using JavaScript(JS) Fetch API and build tool webpack. HTTP is a protocol for fetching resources, a way to communicate with a server, two of the most common requests are GET and POST, we will start with the get request. theWhiteFox Fetch API Webpack Basics repo

Fetch API is a JavaScript Application interface API that makes HTTP requests simpler, cleaner & more logical, using JS promises. "Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function." Asynchronous JavaScript

webpack is mainly a JavaScript static file / module bundler to use in the browser installed with NPM, and convert the modules into static assets.

Fetch API lets see how to use it to make asynchronous HTTP requests.

HTTP Requests with thier Create Read Update Delete (CRUD) equivalent

HTTP VerbCRUDEntire Collection (e.g. /users)Specific Item (e.g. /user/{id})
POSTCreate201 (Created), 'Location' header with link to /users/{id} containing new ID.404 (Not Found), 409 (Conflict) if resource already exists..
GETRead200 (OK), list of users. Use pagination, sorting and filtering to navigate big lists.200 (OK), single user. 404 (Not Found), if ID not found or invalid.
PUTUpdate/Replace405 (Method Not Allowed), unless you want to update/replace every resource in the entire collection.200 (OK) or 204 (No Content). 404 (Not Found), if ID not found or invalid.
PATCHUpdate/Modify405 (Method Not Allowed), unless you want to modify the collection itself. 200 (OK) or 204 (No Content).404 (Not Found), if ID not found or invalid.
DELETEDelete405 (Method Not Allowed), unless you want to delete the whole collection—not often desirable.200 (OK). 404 (Not Found), if ID not found or invalid.

Yeah let's code!

Create a basic fetch function called fetchText, using async await. readme is a local text file.

1async function fetchText() {
2 let response = await fetch('./readme.txt');
3 let data = await response.text();
4 console.log('fetchText: ' + data)
5}
6
7fetchText();
8
9async function fetchText2() {
10 let response = await fetch('./non-existence.txt');
11
12 console.log(response.status); // 404
13 console.log(response.statusText); // Not Found
14
15 if (response.status === 200) {
16 let data = response.text();
17 // handle data
18 console.log('fetchText2: ' + data)
19 }
20}
21
22fetchText2();

webpack

1const path = require('path');
2
3module.exports = {
4 entry: [
5 "@babel/polyfill",
6 './src/js/app.js',
7 './src/sass/app.scss'
8 ],
9 output: {
10 path: path.resolve(__dirname, 'dist/'),
11 filename: 'js/main.js'
12 },
13 module: {
14 rules: [
15 {
16 test: /\.m?js$/,
17 exclude: /(node_modules|bower_components)/,
18 use: {
19 loader: 'babel-loader',
20 options: {
21 presets: ['@babel/preset-env'],
22 plugins: ['@babel/plugin-proposal-object-rest-spread']
23 }
24 }
25 }, {
26 test: /\.scss$/,
27 exclude: /node_modules/,
28 use: [
29 {
30 loader: 'file-loader',
31 options: { outputPath: 'css/', name: '[name].min.css'}
32 },
33 'sass-loader'
34 ]
35 }
36 ]
37 },
38 devServer: {
39 contentBase: path.join(__dirname, './'),
40 compress: true,
41 port: 3000
42 }
43};
Further Reading
JavaScript Fetch APIMDN Using promises
freecodecamp most-popular-ways-http-request-in-JSibm http-requests
Laravel APIAPIs