# 12. XMLHttpRequest

XMLHttpRequest 객체를 사용하여 서버와 상호작용을 할 수 있습니다. XMLHttpRequest 를 사용하면 페이지의 새로고침 없이 data 를 받아오고 업데이트 할 수 있습니다.

JSON, XML, HTML 그리고 일반 텍스트 형식 등을 포함한 다양한 포맷을 주고 받을 수 있습니다

### Json server

[json-server](https://github.com/typicode/json-server)

```
npm i -g json-server
```

**DB.json**

```
{
  "posts": [
    {
      "page": "1",
      "id": 1
    },
    {
      "page": "1",
      "id": 2
    },
  ],
  "comments": [
    {
      "id": 1,
      "body": "some comment",
      "postId": 1
    }
  ],
  "profile": {
    "name": "typicode"
  }
}
```

**onreadystatechange**

특정상태에 따른 행동을 정의합니다. 서버 응답에 따른 로직을 작성합니다.

```javascript
httpRequest.onreadystatechange = function(){};
```

**open, send**

open과 send 를 이용하여 서버로 요청을 보낼 수 있습니다.

```javascript
httpRequest.open(method, URL, true); // true 는 비동기 여부입니다.
httpRequest.send(null);
```

POST 요청시 데이터를 담아야할 때 send 에 데이터를 담아서 보낼 수 있습니다.

**setRequestHeader**

```javascript
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
```

**readyState, status**

readyState 응답의 상태, status 는 http 의 응답 상태 코드입니다.

```javascript
if (httpRequest.readyState === XMLHttpRequest.DONE) {
    // 이상 없음, 응답 받았음
} else {
    // 아직 준비되지 않음
}
```

* 0 (uninitialized) - (request가 초기화되지 않음)
* 1 (loading) - (서버와의 연결이 성사됨)
* 2 (loaded) - (서버가 request를 받음)
* 3 (interactive) - (request(요청)을 처리하는 중)
* 4 (complete) - (request에 대한 처리가 끝났으며 응답할 준비가 완료됨)

```javascript
if (httpRequest.status === 200) {
    // 이상 없음!
} else {
    // 요구를 처리하는 과정에서 문제가 발생되었음
    // 예를 들어 응답 상태 코드는 404 (Not Found) 이거나
    // 혹은 500 (Internal Server Error) 이 될 수 있음
}
```

### 예제

```javascript
var httpRequest = new XMLHttpRequest()

httpRequest.open('GET', 'http://localhost:3000/posts', true)
httpRequest.send()

httpRequest.onreadystatechange = function() {
  if (httpRequest.readyState === XMLHttpRequest.DONE) {
    if (httpRequest.status === 200) {
      console.log(JSON.parse(httpRequest.responseText))
    } else {
      alert('데이터를 받아오지 못했습니다.');
    }
  }
}
```

### 비동기 작업을 동기처럼 동작하게 만드는 방법 <a href="#ba72" id="ba72"></a>

### Callback과 Promise, Async/Await의 차이점 <a href="#ba72" id="ba72"></a>

비동기 작업이란 언제 끝날지 모르는 작업을 의미한다.\
하지만 우리는 코드를 작성할 때 비동기를 동기처럼 보장받아야하는 경우가 생기는데, 이때 Callback, Promise, Async/Await 의 힘을 빌리게된다.![Image for post](https://miro.medium.com/max/60/1*SL_Kyf1N__ohqJCH47LiIw.png?q=20)![Image for post](https://miro.medium.com/max/3192/1*SL_Kyf1N__ohqJCH47LiIw.png)순서를 보장 받지 못한다

**1. Callback**\
먼저 Callback 을 이용하여 이 문제를 해결해보자.\
각각의 fetcher 에서 다음 작업을 호출하게 되는데, 이렇게 하면 우리가 순차 보장이 가능하다.\
️👮🏻‍♀ ️하지만 스케쥴 관리해야될 함수가 많아진다면 가독성이 현저하게 떨어지게되고, callback 앞 뒤로 다른 코드가 들어가면서 작업의 분리가 깔끔하게 되지 않는 문제가 있다.

![Image for post](https://miro.medium.com/max/2824/1*3lX0Dpol0v9aLYNI7IDUtw.png)

**2. Promise**\
Callback 의 단점을 보완한게 Promise 이다. Promise는 then 이라는 함수를 이용해 작업 단위로 함수를 쪼개고, Resolve와 Reject Callback 을 이용해 상황에 맞게 값을 전달한다.

![Image for post](https://miro.medium.com/max/2572/1*0cOjERNPaWGJXcm3IHCJMg.png)

👮🏻‍♀️ 가독성 측면에서는 Callback 보다 좋아졌지만, Promise 인터페이스에 의존해야된다는 문제가 있다. 예를들면 then 안에 코드가 묶인다거나 error 처리를 위해 try/catch 를 사용하는 경우 Promise 의 then/catch 안에서 하는 에러와 중복으로 처리를 해야되는 문제가 있다.

**3. Async/Await**

Promise 의 단점을 보완한 것이 Async/Await 이다.\
Async Function 을 만들고 내부에서 Await 을 이용하여 스케쥴 순서를 정하게된다. 가독성이 좋고, 인터페이스에 묶이지 않기 때문에 코드 분리가 손쉽고모듈화하기도 좋다.

![Image for post](https://miro.medium.com/max/2860/1*RF5SLq44iTmbEVQQuMocew.png)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://simplejs.gitbook.io/olaf/12.-xmlhttprequest.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
