ajax 수업

ajax - API 활용-1 (unsplash.com와 nytimes.com)

줄라이퍼스트 2020. 2. 27. 17:31

※  1. unsplash - API 사용하여 이미지 검색하기

 

https://unsplash.com/developers 사이트에 접속을하여 회원가입!

회원 가입을 한 후

https://unsplash.com/oauth/applications 접속을 하여  애플리케이션을 만든후  api key를 발급받는다

 

 

index.html

 

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Make Asynchronous Requests</title>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    <link rel="stylesheet" href="./css/styles.css">
    
</head>
<body>
    <header class="masthead">
        <h1>What are you interested in today?</h1>

        <div class="site-container">
            <form action="#" id="search-form">

                <label for="search-keyword" class="visuallyhidden">
                    what are you interested in today?
                </label>

                <input type="text" id="search-keyword" placeholder="search" required>
                <input id ="submit-btn" type="submit" value="Submit">

            </form>           
        </div>
    </header>
    <div id="response-container">
        <div id="response-container"></div>
    </div>
    <script src="app.js"></script>
</body>
</html>

 

style.css

 

html {
    box-sizing: border-box;
}

*,
*::before,
*::after {
    box-sizing: inherit;
}

body {
    background: #fafbfc;
    font-family: OpenSans, sans-serif;
    margin: 0;
    padding: 0;
}

.site-container {
    margin: auto;
    max-width: 1200px;
    width: 80%;
}

.masthead {
    background: #2e3d49;
    padding: 2em 0;
}

.masthead h1 {
    color: #ffffff;
    font-weight: normal;
    margin: 0;
    margin-bottom: 0.2em;
    text-align: center;
}

/*** Search Form ***/
#search-form {
    display: flex;
    padding: 1em 0;
}

#search-keyword {
    border: none;
    border-radius: 4px;
    flex-grow: 1;
    margin-right: 1.5em;
    padding: 1.25em 2em;
}

#submit-btn {
    background-color: #15c26b;
    border: none;
    border-radius: 4px;
    color: #ffffff;
    cursor: pointer;
    padding: 1em 4em;
    text-transform: uppercase;
}

#submit-btn:hover {
    background-color: #12a159;
}


/*** Response Container ***/
#response-container {
    margin-top: 2em;
}

/*** Image Styline ***/
figure {
    margin: 0;
    margin-bottom: 2em;
    position: relative;
    text-align: center;
}

figure img {
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
    max-width: 100%;
    width: 100%;
}

figcaption {
    bottom: 5px;
    background: rgba(0, 0, 0, 0.5);
    color: #ffffff;
    font-size: 14px;
    padding: 0.8em 1.4em;
    position: absolute;
    width: 100%;
}



/*** Helpers ***/
.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
    white-space: nowrap; /* 1 */
}

 

 

app.js

 

(function(){
	const form = document.querySelector("#search-form");
	const searchField = document.querySelector("#search-keyword");
	let searchedForText;
	const responseContainer = document.querySelector("#response-container");


	const unsplashedAPIKey = "api키 입력";


	// submt버튼을 눌렀을 때 실행(이벤트를 등록함)
	form.addEventListener('submit',function(e){
		e.preventDefault();
		// ''; << 준이유 초기화한 상태에서 다시 보여주기 위해
		responseContainer.innerHTML ='';
		// searchField는 입력창
		searchedForText = searchField.value;

		// UNSPLASHED API, ajax 사용하려면 xmlhttprequest() 사용
		const unsplashRequest = new XMLHttpRequest();

		// ${searchedForText} => searchField.value 즉 입력한 값이 저기로 들어감
		unsplashRequest.open('GET', `https://api.unsplash.com/search/photos?page=1&query=${searchedForText}`);
		// status 4이면서 다왔고 response가 200번인경우 실행함
		unsplashRequest.onload = addImage;
		// server 측에서 error가 발생 되었을 때
		unsplashRequest.onerror = function(err){
			requestError(err,'image');
		}
		unsplashRequest.setRequestHeader('Authorization', `Client-ID ${unsplashedAPIKey}`);
		unsplashRequest.send();


		function addImage(){
			let htmlContent='';

			// josn 데이터를 javaScipt에서는 텍스트로 인식을 하고 있으므로 javaScript object로 변환해줘야함
			// 가장 흔한 예가 Ajax를 사용할 경우이다. Ajax로 호출을 하고 결과값으로 받은responseText로 JSON을 받았을 경우에는 
			// 그냥 Text이기 때문에 Object로 변환해 주어야 한다.			
			const data = JSON.parse(this.responseText);
            
			// data가 존재하고 data.results true가 되고 data.results[0] 배열의 인덱스는 object로 되어있음			
			if(data && data.results && data.results[0]){
				// data.results[0] 에있는 것을 firstImage안에 넣음
				const firstImage = data.results[0];
				// json 데이터에서 urls.regular를 가져옴
				// firstImage에 user.name 것을 가져옴
				htmlContent =`<figure>				
					<img src="${firstImage.urls.regular}" alt="${searchedForText}">
					<figcaption>${searchedForText} by ${firstImage.user.name}</figcaption>
					</figure>`;
			} else{
				htmlContent = '<div class ="error-no-image">No image avaiable<div>';
			}
			responseContainer.insertAdjacentHTML('afterbegin',htmlContent);
		}
	});
})();

 

 

※  1. 실행화면

 

1. 실행화면 - rainbow를 입력하였을 때

 

 

 

 

1-1. 실행화면 - rainbow를 검색하였을 때

 

 

※ 2. nytimes- API 사용

 

https://developer.nytimes.com

 

https://developer.nytimes.com/

 

developer.nytimes.com

사이트에 접속을하여 회원가입!

 

https://developer.nytimes.com/get-started

 

https://developer.nytimes.com/get-started

 

developer.nytimes.com

마찬가지로 api키를 발급을 받아야되는데 이 주소를 클릭하면 api를 받는것에대해 설명이 나와있다.

영어로 되어 있어 읽기 어려우시면 구글번역으로 보시면 됩니당

 

html파일과 css파일은 기존것을 사용하고 nyt API 만 추가한다.

 

app.js

 

(function(){
	const form = document.querySelector("#search-form");
	const searchField = document.querySelector("#search-keyword");
	let searchedForText;
	const responseContainer = document.querySelector("#response-container");

	const nytAPIKey = "발급받은 apikey 입력";
	const unsplashedAPIKey = "발급받은 apikey 입력";




	// submt버튼을 눌렀을 때 실행(이벤트를 등록함)
	form.addEventListener('submit',function(e){
		e.preventDefault();
		// ''; << 준이유 초기화한 상태에서 다시 보여주기 위해
		responseContainer.innerHTML ='';
		// searchField는 입력창
		searchedForText = searchField.value;

		// UNSPLASHED API, ajax 사용하려면 xmlhttprequest() 사용
		const unsplashRequest = new XMLHttpRequest();

		// ${searchedForText} => searchField.value 즉 입력한 값이 저기로 들어감
		unsplashRequest.open('GET', `https://api.unsplash.com/search/photos?page=1&query=${searchedForText}`);
		// status 4이면서 다왔고 response가 200번인경우 실행함
		unsplashRequest.onload = addImage;
		// server 측에서 error가 발생 되었을 때
		unsplashRequest.onerror = function(err){
			requestError(err,'image');
		}
		unsplashRequest.setRequestHeader('Authorization', `Client-ID ${unsplashedAPIKey}`);
		unsplashRequest.send();


		function addImage(){
			let htmlContent='';

			// josn 데이터를 javaScipt에서는 텍스트로 인식을 하고 있으므로 javaScript object로 변환해줘야함
			// 가장 흔한 예가 Ajax를 사용할 경우이다. Ajax로 호출을 하고 결과값으로 받은responseText로 JSON을 받았을 경우에는 
			// 그냥 Text이기 때문에 Object로 변환해 주어야 한다.			
			const data = JSON.parse(this.responseText);
			// data가 존재하고 data.results true가 되고 data.results[0] 배열의 인덱스는 object로 되어있음			
			if(data && data.results && data.results[0]){
				// data.results[0] 에있는 것을 firstImage안에 넣음
				const firstImage = data.results[0];
				// json 데이터에서 urls.regular를 가져옴
				// firstImage에 user.name 것을 가져옴
				htmlContent =`<figure>				
					<img src="${firstImage.urls.regular}" alt="${searchedForText}">
					<figcaption>${searchedForText} by ${firstImage.user.name}</figcaption>
					</figure>`;
			} else{
				htmlContent = '<div class ="error-no-image">No image avaiable<div>';
			}
			responseContainer.insertAdjacentHTML('afterbegin',htmlContent);
		}

		 //NYT API
		 const articleRequest = new XMLHttpRequest();
		 articleRequest.onload = addArticles;
		 articleRequest.onerror = function (err) {
			 requestError(err, 'articles');
		 }
		 articleRequest.open('GET', `http://api.nytimes.com/svc/search/v2/articlesearch.json?q=${searchedForText}&api-key=${nytAPIKey}`);
		 articleRequest.send();
 
		 function addArticles() {
			 let htmlContent = '';
			 const data = JSON.parse(this.responseText);
			 if (data && data.response.docs && data.response.docs[0]) {			
 
				 htmlContent = '<ul>' + data.response.docs.map(article => `<li class="article">
					 <h1><a href="${article.web_url}" target="_blank">${article.headline.print_headline}</h1></a>
					 <h2>${article.headline.main}</h2>
					 <p>${article.snippet}</p></li>`
				 ).join('') + '</ul>';
 
 
			 } else {
				 htmlContent = '<div class="error-no-articles">No articles available </div>';
			 }
 
			 responseContainer.insertAdjacentHTML('afterend', htmlContent);
		 }




	});
})();

 

※ 2. 실행화면

 

 

2-1. 실행화면 - iphone을 검색했을때 해당이미지와 뉴욕타임스 기사가 나온다.

 

2.2- 실행화면 - 기사를 클릭하면 뉴욕타임스 홈페이지에 있는 기사를 볼 수있다.

 

'ajax 수업' 카테고리의 다른 글

ajax - API 활용-2 (unsplash.com와 nytimes.com)  (0) 2020.02.27