Let’s see how a request to the server is made in JavaScript.
XML is an object that is supported in all most every browser. Before XML whenever there was a change in the data the browser had to reload to reflect the changes. XML separated handling of data from displaying contents on the screen which is handled by HTML by solely managing data making it possible to reflect changes without having to reload.
Moreover, XML also provides an asynchronous feature when fetching data that enabled handling other tasks during data processing.
As the data is transformed into a plain text form that can be understandable by almost every consumer (human, machines) the loss of data is minimum.
XMLHttpRequest
First, instantiate the XMLHttpRequest object then use .open and .send to request data. For the asynchronous way, use .onreadystatechange to catch the moment when the data is ready. For the synchronous way, we can just use the returned data as the task is done in order.
Asynchronous
var xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) { // 데이터가 정상적으로 왔는지 확인 https://www.w3schools.com/xml/ajax_xmlhttprequest_response.asp
console.log(xhttp.responseText) // 반환된 데이터 (데이터 활용에 필요한 코드가 들어 가는 위치)
}
}
xhttp.open('GET', API, true) //method: 'GET' or 'POST' / 파일위치 / 비동기 또는 동기
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //POST 방식에서 헤더지정
xhttp.send() // POST의 경우 매개변수로 데이터 전송
Synchronous
var xhttp = new XMLHttpRequest()
xhttp.open('GET', API, false)
xhttp.send()
console.log(xhttp.responseText) // 반환된 데이터 (데이터 활용에 필요한 코드가 들어 가는 위치)
Methods
XML
XML has two methods, GET and POST. GET is faster and simple but it has a data limit and is not secure. While POST is slower but has no data limit and is secure. So POST is often used when user data needs to be transferred, for example, when a form is submitted.
Properties and Methods in response
- responseText: data is returned as a string
- response XML: data is returned as an XML
- getResponseHeader(): gets a specific header
- getAllResponseHeaders(): gets all header
Fetch
Fetch is a more modern way of getting data from a server. This Web API is mainly used currently because of its simpler syntax compared to its predecessor.
fetch - async, await syntax
const API = 'https://api.github.com/users'
async function fetchUsers() {
const res = await fetch(API)
const data = await res.json()
console.log(data)
}
fetch - .then syntax
function fetchUsers() {
fetch(API).then((res) => {
return res.json()
}).then(data => {
console.log(data)
})
}
Parameters
It is possible to send additional data in the URL. The formats are, for the first parameter, the question mark(?) followed by the key and value, and for the second and afterward, ampersand (&) followed by the key and value
http://localhost:8080/main?para1=dd¶2=cc'
To get the value from the parameter we can use the URL object and get the value with the key
var url = new URL('http://localhost:8080/main?dd=dd');
var c = url.searchParams.get("dd");
In this writing, we have explored HTTP requests in JavaScript and I hope it was helpful
References
'Frontend > JavaScript' 카테고리의 다른 글
Module System (0) | 2023.03.29 |
---|---|
Webpack (1) | 2023.03.29 |
Day / Night Mode with JavaScript (1) | 2023.03.24 |
How to Tell PC from Mobile in A Responsive APP (1) | 2023.03.23 |
Modal (0) | 2023.03.14 |