-
Requests II (fetch)Java Script 2020. 9. 1. 16:27
1. fetch() GET Requests I
fetch()기능 :
- API에 필요한 관련 정보가 포함 된 요청 객체를 만듭니다.
- 해당 요청 객체를 제공된 API 엔드 포인트로 보냅니다.
- API가 다시 보낸 정보와 함께 promise의 상태를 포함하는 응답 객체로 궁극적으로 확인되는 promise를 반환합니다.
- fetch()GET 및 POST 요청을 만드는 데 사용 됩니다.
- 돌아 오는 응답의 상태를 확인
- 발생할 수있는 오류 포착
- 성공적인 응답을 받아 웹 페이지에 렌더링
/*1. First, call the fetch() function and pass it this URL as a string: This first argument determines the endpoint of the request. 2. Chain a .then() method to the end of the fetch() function and pass it the success callback arrow function as its first argument. The success callback function takes one parameter, response. .then() will fire only after the promise status of fetch() has been resolved. 3.Inside of the response callback function, check the ok property of response inside of a conditional statement. In the code block of the conditional statement, return response.json(). The reason we’re testing the ok property of the response object is that it will be a Boolean value. If there were no errors response.ok will be true and then your code will return response.json(). 4. Below the curly braces of the conditional statement, create a new error with this code: Your code will throw this error when response.ok is falsy. 5. Add a second argument to .then(), it will be an arrow function that will handle our failures. Separate the first callback function from the second with a comma. The second callback function takes a single parameter, networkError. In the code block of the second callback function, log networkError.message to the console. If we could not reach the endpoint at all, e.g., the server is down, then we would get this networkError. 6. Chain another .then() method to the end of the first .then() method. Pass the new .then() method a callback function that takes jsonResponse as its parameter and return jsonResponse. The second .then()‘s success callback won’t run until the previous .then() method has finished running. It will also not run if there was an error was thrown previously. */ fetch('https://api-to-call.com/endpoint').then(response => { if (response.ok) { return response.json(); } throw new Error('Request failed!'); }, networkError => { console.log(networkError.message).then(jsonResponse =>{ return jsonResponse; } ); })
2. fetch() POST Requests I
/* 1. Call the fetch() function, pass it the URL below as a string as its first argument, and pass it an empty object ({}) as its second argument. We’re calling fetch() and providing an endpoint. In the next step we’ll fill in the empty object with the necessary information. 2. The settings object you passed to the fetch() function will contain two properties: method, with a value of 'POST', and body, with a value of JSON.stringify({id: '200'}). This second argument determines that this request is a POST request and what information will be sent to the API. 3. Chain a .then() method to the fetch() function and pass it the success callback function as its first parameter. Pass in response as an argument for the callback function. Leave the code block of the callback function empty for now. The code inside .then() will execute when the promise returned from fetch() is resolved. 4. Inside the callback function’s code block, check the ok property of the response object inside of a conditional statement. In the code block of the conditional statement, return response.json(). When returned, this information will be passed on to the next .then() callback function. 5. Below the curly braces of the conditional statement, create a new error with this code: This error will be raised if we get back some status error. 6. Create the failure callback function. This function takes a single parameter, networkError. Separate the first callback function from the second with a comma. This function is still inside of the .then() method. In the code block of the function you just made, log networkError.message to the console. 7. Chain another .then() method to the end of the first .then() method. In the new .then() method, create an arrow callback function that takes jsonResponse as its parameter. Then in the code block return jsonResponse. The purpose of this step is to view the JSON that was returned from the previous .then(). */ fetch('https://api-to-call.com/endpoint', { method: 'POST', body: JSON.stringify({id: '200'}) }).then(response => { if (response.ok) { return response.json(); } throw new Error('Request failed!'); }, networkError => console.log(networkError.message) ).then( jsonResponse => { return jsonResponse; } );
3.async GET Requests I
- async약속을 반환 하는 함수를 사용합니다 .
- awaitasync함수 에서만 사용할 수 있습니다 . await약속이 해결 될 때까지 기다리는 동안 프로그램을 실행할 수 있습니다.
- A의 try...catch문은 코드 try블록이 실행됩니다 예외 / 오류가 발생에서의 코드 catch문이 실행됩니다.
/* 1. create an arrow function using the async keyword and save it to a const getData. The async keyword will ensure that the function returns a promise. 2. In the code block for getData, we should add a try statement with an empty code block. Below the try statement’s code block, add a catch(error) statement. The code in the try block will send a request and handle the response. The catch statement will then take care of an error if it is thrown. 3. Inside the catch code block, log error to the console. Since this exercise is an example, we’re using console.log() to view the error. Generally, developers create a more sophisticated way of handling the error, like redirecting their users to another page, but logging is fine for us at the moment. 4. We should start by using the await keyword before calling fetch(). Pass in the following URL, as a string, to the function as its first argument: We’ll have to save the returned promise in a variable called response using the const keyword. response will save the the response of endpoint once that information has been sent back. 5. Under response, create a conditional statement that checks if the ok property of the response object evaluates to a truthy value. 6.Inside the code block of the conditional statement, await the resolution of calling the .json() method on response. Save the returned object to a variable called jsonResponse using the keyword const. Since .json() is an asynchronous method we have to await until the promise status is resolved. Then we store the value to know what data the JSON holds. 7.Return jsonResponse directly below the code you wrote in the previous step. Normally, we’d want to use the information from jsonResponse in a different manner. In this exercise, we’re practicing how to write the boilerplate code. 8.Below the conditional statement, throw a new Error. The message the error should raise is ‘Request failed!’. */ const getData = async () => { try { const response = await fetch('https://api-to-call.com/endpoint'); if (response.ok) { const jsonResponse = await response.json(); return jsonResponse ; } throw new Error('Request failed!'); } catch (error) { console.log(error); } };
4. async POST Requests I
/* 1.At the top of main.js create an async arrow function and save it to a const getData(). The async keyword will ensure that the function returns a promise. 2.In the code block for getData, we should add a try statement with an empty code block. In case things go wrong, we need some code to handle that. Below the try code block, add a catch statement and pass in error as an argument. Then, in the catch statement code block, log error to the console. 3.We now have to consider what we want to do inside of the try code block. Since we are making a POST request, we should start by using the await keyword before calling the fetch() function. We will have to save the returned promise in a variable called response using the const keyword. 4.In the fetch() call that we just made, pass in the following URL to the function as a string for the first argument: Then as our second argument, let’s pass in an empty object for now. 5. Let’s now fill in the request options in our second argument. First, add the method property and the value is 'POST'. Then we have to include a body property and the value is JSON.stringify({id: 200}). Remember to separate the properties with a comma. 6.After the code block of response, we should create an if statement that checks the ok property of the response object. Inside the code block of the conditional statement, await the resolution of calling the .json() method on response. Save the returned object to a variable called jsonResponse using the keyword const. 7.Now that we have what we want, we should return jsonResponse directly below the code written in the previous step. Like with previous boilerplate exercises, we’re practicing writing code. Normally, we would want to do more beyond this step of returning jsonResponse. 8.Below the if conditional, throw a new Error() with the message 'Request failed!' */ const getData = async () => { try { const response = await fetch('https://api-to-call.com/endpoint',{ method: 'POST', body: JSON.stringify({id: 200}) }); if (response.ok) { const jsonResponse = await response.json(); return jsonResponse } throw new Error('Request failed!'); } catch(error) { console.log(error); } }
-
GET 및 POST 요청은 다양한 방법으로 생성 될 수 있습니다.
-
AJAX를 사용하여 API에서 데이터를 비동기 적으로 요청합니다. fetch()및 async/ await는 각각 ES6 (약속) 및 ES8에서 개발 된 새로운 기능입니다.
-
Promise는 요청에서 결국 반환 될 데이터를 나타내는 새로운 유형의 JavaScript 개체입니다.
-
fetch()요청을 생성하는 데 사용할 수있는 웹 API입니다. fetch()약속을 반환합니다.
-
에서 .then()반환 된 promise를 처리하기 위해 메서드를 연결할 수 있습니다 fetch().
-
이 .json()메서드는 반환 된 promise를 JSON 개체로 변환합니다.
-
async Promise를 반환하는 함수를 만드는 데 사용되는 키워드입니다.
-
await Promise가 해결되는 동안 메시지 큐를 통해 계속 이동하도록 프로그램에 지시하는 데 사용되는 키워드입니다.
-
await로 선언 된 함수 내에서만 사용할 수 있습니다 async.
'Java Script' 카테고리의 다른 글
ASYNC AWAIT (0) 2020.08.26 JAVASCRIPT PROMISES (0) 2020.08.24 WorkAround (0) 2020.08.19 Message Mixer (0) 2020.08.18 Modules (0) 2020.08.13