React JS 앱에서 Spotify API를 사용하는 방법

27853 단어 reacttutorialspotify
이 튜토리얼에서는 애플리케이션에서 Spotify API를 사용하는 방법을 배웁니다.

만약 질문이 있다면

GitHub 파일: https://github.com/dom-the-dev/spotify-with-react



저도 차근차근 video

내용 목록


  • Create Spotify App
  • Setup React Application
  • Authentication
  • Access Token
  • Logout
  • Fetching Data
  • Displaying Data

  • 스포티파이 앱 만들기

    First, we need to create a Spotify App at Spotifys developer dashboard. For that you need to login at https://developer.spotify.com/dashboard/login .

    녹색 버튼 "앱 만들기"를 클릭합니다. Modal에서는 앱 이름과 설명을 설정해야 합니다. 약관을 확인하고 만들기 버튼을 누릅니다.

    Spotify 앱 개요로 리디렉션됩니다. 여기에서 나중에 반응 앱에서 필요할 클라이언트 ID를 얻습니다.

    이 단계를 완료하려면 리디렉션 URI를 설정해야 합니다. "설정 편집"을 클릭하십시오. "리디렉션 URI"에서 http://localhost:3000을 입력하고 추가를 클릭하여 확인한 다음 설정을 저장합니다.

    이제 코딩을 시작할 준비가 되었습니다.

    React 애플리케이션 설정

    Open your terminal and create a new react application with following command:

    npx create-react-app spotify-react
    

    This creates a complete react application. With cd spotify-react && yarn start you jump into the projects directy and start the development server which then runs at http://localhost:3000 by default.

    (If for whatever reason the port is not 3000 make sure to change the redirect url in your spotify app settings.)

    입증

    To be able to use the API, the user needs to be authenticated with his Spotify Account. For that case we need to create a link which leads us to the Spotify Authentication/Login page.

    This links consists of the following params:

    • Endpoint
    • Client ID
    • Redirect URI
    • Response Type

    Let's start coding, open up App.js and remove all that stuff you don't need, so you app will look similiar to this:

    import './App.css';
    
    function App() {
    
        return (
            <div className="App">
                <header className="App-header">
    
                </header>
            </div>
        );
    }
    
    export default App;
    
    

    Now let's add the variables which we then use for our authentication link.

    (You get the CLIENT_ID from the Spotify App Overview, mentioned at the beginning.)

    const CLIENT_ID = "+++++++++++++++++++++++++++++"
    const REDIRECT_URI = "http://localhost:3000"
    const AUTH_ENDPOINT = "https://accounts.spotify.com/authorize"
    const RESPONSE_TYPE = "token"
    

    Now we can create the link in the return of our App.js which looks like this:

     <a href={`${AUTH_ENDPOINT}?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=${RESPONSE_TYPE}`}>Login to Spotify</a>
    

    Let's open http//:localhost:3000 in your browser. When you click on the Login to Spotify link, you will be redirected to the Spotify Authentication page.

    Either you are already logged in, than you just need to accept the terms, or you need to login with your Spotify Account credentials.

    After accepting the terms you will be redirected back to the app at localhost:3000 .
    A hash is passed to the URL which contains the access token which we need to authorize the API calls.

    액세스 토큰

    As we want to check for the token as soon as we come back, we use the useEffect from react.
    Then we check the URL for the hash and extract the token by performing some tasks. After that we store the token in a state variable with help of the useState hook as well as we save the token in our localeStorage.

    Import the useEffect as well as the useState hook to your application.

    import {useEffect, useState} from 'react';
    

    Now create the state variable for the token and set it to an empty string by default.

    const [token, setToken] = useState("")
    

    The useEffect function will look like this:

    useEffect(() => {
        const hash = window.location.hash
        let token = window.localStorage.getItem("token")
    
        if (!token && hash) {
            token = hash.substring(1).split("&").find(elem => elem.startsWith("access_token")).split("=")[1]
    
            window.location.hash = ""
            window.localStorage.setItem("token", token)
        }
    
        setToken(token)
    
    }, [])
    

    Let me explain what happens in here:
    When we open the app, we check if we have a hash or we already have a token saved in our localStorage.
    If we do have a token stored, we simply continue by setting our token state variable.
    If we don't have a token, we check if we have a hash. If so we perform tasks on that string to extract the token.

    We substring the hash at the beginning. We split the String by the ampersands. Then we search vor that element which contains access_token. This element than again will be split at the equal sign. The array we get contains the token at index 1.

    Once we got the token we save it in our localStorage and reset the hash.

    로그 아웃

    To logout we simply create a function which removes the token from our localStorage as well as we set the state token back to an empty string.

    const logout = () => {
        setToken("")
        window.localStorage.removeItem("token")
    }
    

    Let's add the Logout Button to our app, rendering conditionally depending on token state.

    The intermediate stand of App.js should now look like this

    
    function App() {
        const CLIENT_ID = "+++++++++++++++++++++++++++++"
        const REDIRECT_URI = "http://localhost:3000"
        const AUTH_ENDPOINT = "https://accounts.spotify.com/authorize"
        const RESPONSE_TYPE = "token"
    
        const [token, setToken] = useState("")
    
        useEffect(() => {
            const hash = window.location.hash
            let token = window.localStorage.getItem("token")
    
            if (!token && hash) {
                token = hash.substring(1).split("&").find(elem => elem.startsWith("access_token")).split("=")[1]
    
                window.location.hash = ""
                window.localStorage.setItem("token", token)
            }
    
            setToken(token)
    
        }, [])
    
        const logout = () => {
            setToken("")
            window.localStorage.removeItem("token")
        }
    
        return (
            <div className="App">
                <header className="App-header">
                    <h1>Spotify React</h1>
                    {!token ?
                        <a href={`${AUTH_ENDPOINT}?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=${RESPONSE_TYPE}`}>Login
                            to Spotify</a>
                        : <button onClick={logout}>Logout</button>}
                </header>
            </div>
        );
    }
    
    export default App;
    

    데이터를 가져 오는 중

    Now we are ready to start with the fun part. In this tutorial we are searching for artists and display some informations like name and their profile image. Check out the 104671610 for way ress ress.

    먼저 검색어를 유지하는 상태와 가져온 데이터를 유지하는 상태의 두 가지 새 상태를 만듭니다.

    const [searchKey, setSearchKey] = useState("")
    const [artists, setArtists] = useState([])
    


    다음 명령으로 HTTP 요청을 처리할 axios을 설치하십시오.

    yarn add axios
    


    앱으로 가져오기

    import axios from 'axios";
    


    이제 searchArtists 함수를 만듭니다. axios를 사용하여 Spotify API 엔드포인트에 대한 GET 요청을 수행합니다. 요청 구성으로 Bearer Authorization 및 토큰이 있는 헤더가 포함된 객체를 전달합니다. 여기에서 artist 으로 설정된 검색어와 검색 유형을 포함하는 params 객체도 있습니다.
    요청이 완료되고 가져오기가 성공하면 응답이 아티스트 상태로 설정됩니다.

    const searchArtists = async (e) => {
        e.preventDefault()
        const {data} = await axios.get("https://api.spotify.com/v1/search", {
            headers: {
                Authorization: `Bearer ${token}`
            },
            params: {
                q: searchKey,
                type: "artist"
            }
        })
    
        setArtists(data.artists.items)
    }
    


    검색을 수행하려면 앱에 양식을 추가할 수 있습니다.

    <form onSubmit={searchArtists}>
        <input type="text" onChange={e => setSearchKey(e.target.value)}/>
        <button type={"submit"}>Search</button>
    </form>
    


    거의 다 왔습니다.

    선적 서류 비치 데이터 표시

    The last step is to display the data in our application. For that we let's create the renderArtists function and call it inside the return of our App.js .

    const renderArtists = () => {
        return artists.map(artist => (
            <div key={artist.id}>
                {artist.images.length ? <img width={"100%"} src={artist.images[0].url} alt=""/> : <div>No Image</div>}
                {artist.name}
            </div>
        ))
    }
    
    {renderArtists()}
    
    Visit your browser at . Spotify 계정으로 로그인하고 검색 필드에 아티스트를 입력하고 앱에서 렌더링된 데이터를 확인합니다.


    읽어 주셔서 감사합니다! 이 기사가 마음에 드셨으면 합니다. 피드백을 남겨주세요! :)


    http://localhost:3000 단계별 비디오

    좋은 웹페이지 즐겨찾기