Section 18: Network Requests - Sending Http Requests via JavaScript
The goals
๐ช๐ปWhat & Why?
โ๐ปXMLHttpRequest & fetch() API
๐๐ปJSON Data & FormData
๐๐ปGETting Data, POSTing Data
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts');
xhr.responseType = 'json';
xhr.onload = function() {
// const listOfPosts = JSON.parse(xhr.response);
// we can do like this but there is another simple way
const listOfPosts = xhr.response;
// console.log(xhr.response);
// json type so we can't use it as like array
}
xhr.send()
JSON ๋ฐ์ดํฐ ํํค์น๊ธฐ
์ผ๋ฐ์ ์ผ๋ก ๋ฐ์ดํฐ๋ ํด๋ผ์ด์ธํธ ์ธก ์ฝ๋์ ๋ฐฑ์๋("์๋ฒ") ์ฌ์ด์์ "JSON" ๋ฐ์ดํฐ๋ก ์ ์ก๋ฉ๋๋ค.
JSON์ JavaScript Object Notation์ ์ฝ์๋ก, ์๋์ ๊ฐ์ต๋๋ค.
{
"name": "Max",
"age": 30,
"hobbies": [
{ "id": "h1", "title": "Sports" },
{ "id": "h2", "title": "Cooking" }
],
"isInstructor": true
}
JSON ๋ฐ์ดํฐ๋ ๊ฐ์ฒด({}), ๋ฐฐ์ด([]), ๋ฌธ์์ด(๋ฐ๋์ ํฐ ๋ฐ์ดํ ์ฌ์ฉ!), ์ซ์(๋ฐ์ดํ ์์ด)์ ๋ถ๋ฆฌ์ธ(๋ฐ์ดํ ์์ด)์ ์ง์ํฉ๋๋ค.
๋ชจ๋ ๊ฐ์ฒด ํค(์: "name")๋ ํฐ ๋ฐ์ดํ๋ก ๋ฌถ์ด์ผ ํฉ๋๋ค. ๋ฐ์ดํ๊ฐ ์๋ ๊ฒฝ์ฐ๋ ์์ ๋ฐ์ดํ์ ๊ฒฝ์ฐ๋ ํ์ฉ๋์ง ์์ต๋๋ค!!
๋ชจ๋ JSON “๊ฐ์ฒด”๋ ๋ฐ์ดํ๋ก ๋ฌถ์ ๋๋ค. ๊ฒฐ๊ตญ์๋ JSON ๋ฐ์ดํฐ๊ฐ ์์ ํ์๋ ํ์์ ๋ฐ์ดํฐ๋ฅผ ํฌํจํ๋ ๋ฌธ์์ด์ด๊ธฐ ๋๋ฌธ์ ๋๋ค.
์ฌ๋ฌ๋ถ์ด ์ง์ ํ ์คํธํด๋ณผ ์ ์์ต๋๋ค - ๋ค์ JSON JavaScript๊ฐ ์๋ ๊ฐ์ฒด๋ฅผ ๊ฐ์ ธ์์ JSON.stringify()๋ฅผ ์ ์ฉํด ๋ณด์ธ์. ๊ทธ๋ฌ๋ฉด JSON ๋ฐ์ดํฐ๋ก ๋ณํ๋ฉ๋๋ค. ๊ฐ๋ฐ ๋๊ตฌ ์ฝ์์์ ๊ทธ๋ ๊ฒ ํ๋ฉด ๊ฒฐ๊ตญ ์์์ ์ดํด๋ณธ ๋๋ก ํ์์ด ์ง์ ๋ ๋ฐ์ดํฐ๊ฐ ํฌํจ๋ ๋ฌธ์์ด์ ์ป๊ฒ ๋ฉ๋๋ค.
const person = { // ์ด๊ฒ์ JSON์ด ์๋๋๋ค - ์ผ๋ฐ("๋ ๊ฒ์") JavaScript ๊ฐ์ฒด์
๋๋ค!
name: 'Max',
age: 30,
hobbies: [
{ id: 'h1', title: 'Sports' },
{ id: 'h2', title: 'Cooking' }
],
isInstructor: true
};
const jsonData = JSON.stringify(person); // JS ๋ฐ์ดํฐ๋ฅผ JSON ๋ฐ์ดํฐ ๋ฌธ์์ด๋ก ๋ณํ
console.log(jsonData); // ์ปดํจํฐ๊ฐ ์ฝ์ ์ ์๋ JSON ๋ฐ์ดํฐ๊ฐ ํฌํจ๋ ๋ฌธ์์ด
console.log(typeof jsonData); // string
๊ธฐ๊ณ์ ๋ํ ๊ตฌ๋ฌธ ๋ถ์์ด ์ฝ๊ณ ์ฌ๋์ด ์ฝ๊ธฐ์๋ ๋์์ง ์๊ธฐ ๋๋ฌธ์ JSON ๋ฐ์ดํฐ๋ฅผ ์ฌ์ฉํฉ๋๋ค.
JSON ๋ฐ์ดํฐ๋ฅผ ์์ ํ๊ณ ์ด๋ฅผ ๋ค์ ์ผ๋ฐ JS ๋ฐ์ดํฐ๋ก ๋ณํํ๋ ค๋ ๊ฒฝ์ฐ JSON.parse()๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค:
const parsedData = JSON.parse(jsonData);
// yields a "raw" JS object/ array etc.
์์๋๋ฉด ์ข์ ์ ๋ณด. ๋ฐ์ดํฐ๋ฅผ JSON์ผ๋ก ๋ณํํ ์ ์๋ ๊ฒ์ ๊ฐ์ฒด๋ก ์ ํ๋์ง ์์ต๋๋ค. ์ซ์, ๋ฐฐ์ด, ๋ถ๋ฆฌ์ธ ๋๋ ๋ฌธ์์ด๋ ๋ณํํ ์๋ ์์ต๋๋ค - JSON์ด ์ง์ํ๋ ๋ชจ๋ ๋ฐ์ดํฐ ์ ํ์ด ๋ณํ ๊ฐ๋ฅํฉ๋๋ค.
const jsonNumber = JSON.stringify(2); // "2"
const jsonText = JSON.stringify('Hi there! I use single quotes in raw JS'); // ""Hi there! ...""
const jsonArray = JSON.stringify([1, 2, 3]); // "[1,2,3]"
const jsonBoolean = JSON.stringify(true); // "true"
๋ค์์ ํผ์ ์ ๋ง๊ธฐ ์ํ ๊ฐ๋จํ ๋ฉ๋ชจ์ ๋๋ค. ๋ฐ๋ชจ ์ ํ๋ฆฌ์ผ์ด์ ์์ "Fetch" ๋ฒํผ์ ํญ์ ๊ธฐ์กด ๋ฐ์ดํฐ๋ฅผ ๋จผ์ ์ง์ฐ์ง ์๊ณ ๋ฐ์ดํฐ๋ฅผ ์ถ๊ฐํฉ๋๋ค. ์ฆ ๋ฒํผ์ ์ฌ๋ฌ ๋ฒ ๋๋ฅด๋ฉด ๋ ๋ง์ ํญ๋ชฉ์ด ๊ณ์ ์ถ๊ฐ๋ฉ๋๋ค.
๋ฌผ๋ก ๋จผ์ ๋ด์ฉ์ ์ง์ฐ๊ณ ์ถ๊ฐํ๋๋ก ์ฝ๋๋ฅผ ์กฐ์ ํ ์๋ ์์ต๋๋ค.
function sendHttpRequest(method, url, data) {
// const promise = new Promise((resolve, reject) => {
// const xhr = new XMLHttpRequest();
// xhr.setRequestHeader('Content-Type', 'application/json');
// xhr.open(method, url);
// xhr.responseType = 'json';
// xhr.onload = function() {
// if (xhr.status >= 200 && xhr.status < 300) {
// resolve(xhr.response);
// } else {
// xhr.response;
// reject(new Error('Something went wrong!'));
// }
// // const listOfPosts = JSON.parse(xhr.response);
// };
// xhr.onerror = function() {
// reject(new Error('Failed to send request!'));
// };
// xhr.send(JSON.stringify(data));
// });
// return promise;
return fetch(url, {
method: method,
// body: JSON.stringify(data),
body: data,
// headers: {
// 'Content-Type': 'application/json'
// }
})
.then(response => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
return response.json().then(errData => {
console.log(errData);
throw new Error('Something went wrong - server-side.');
});
}
})
.catch(error => {
console.log(error);
throw new Error('Something went wrong!');
});
}
1. fetch๋ promise๊ฐ์ฒด๋ฅผ ๋ฐํ, ์ฆ ๋ฐ๋ก ๋ญ ํ ๊ฒ ์์ด ๋ฐ๋ก '.then', '.catch'๋ฑ์ ๋ฉ์๋ ์ฐ๊ฒฐํด์ ์ฌ์ฉ ๊ฐ๋ฅ
2. ์ด ๋ catch๋ ๋คํธ์ํฌ์์ ํฐ ์ค๋ฅ๋ก ํ์ด์ง๊ฐ ์ ง๋ค์ด๋์ง ์๋ ์ด์์ ์๋ฌ๋ฅผ ์บ์นํด๋ด์ง ๋ชปํ๋๋ฐ ์ด๋ฅผ ๋ณด์ํ๊ธฐ ์ํด if๋ฌธ์ ์ฌ์ฉํด์ status๊ฐ ์ ์ (200, 202๋ฑ์ ๊ฒฝ์ฐ)์์๋ง ์ถ๋ ฅ๋๋๋ก ์์ฑ
formData
In JavaScript, a FormData object is a common way to create a bundle of data to send to the server using XMLHttpRequest or fetch.
It replicates the functionality of the HTML form element.
We can think of it as an array of arrays. There is one array for each element that we want to send to the server.
Each element consists of the following three things:
- name: The name of the field.
- value: The value of the field. It can be a String or Blob.
- filename: The file’s name to be saved on the server when a Blob is passed as the second parameter.
Syntax
const formData = new FormData([form]);
Parameter
The formData constructor creates and returns a new FormData object.
If an HTML form element is provided, it automatically captures its fields. This parameter is optional.
Additional data can be added in the FormData object using the formData.append() method.
formData.append(name, value, filename);
The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the fetch() or XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".
You can also pass it directly to the URLSearchParams constructor if you want to generate query parameters in the way a <form> would do if it were using simple GET submission.
An object implementing FormData can directly be used in a for...of structure, instead of entries(): for (const p of myFormData) is equivalent to for (const p of myFormData.entries()).
Sources
https://jsonplaceholder.typicode.com/
JSONPlaceholder - Free Fake REST API
{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB. Tested with XV. As of Oct 2022, serving ~1.7 billion requests each month.
jsonplaceholder.typicode.com
https://developer.mozilla.org/en-US/docs/Web/API/FormData
FormData - Web APIs | MDN
The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the fetch() or XMLHttpRequest.send() method. It uses the same format a form would use if the e
developer.mozilla.org
https://www.educative.io/answers/what-is-a-formdata-object-in-javascript
What is a formData Object in JavaScript?
Contributor: Shubham Singh Kshatriya
www.educative.io