我一直在关注使用 React 和 Spotify Web API 创建基于用户搜索的歌曲的播放列表的教程。到目前为止,我已经成功地设置了访问令牌/身份验证部分,并且还使用 GET 请求来提取用户配置文件信息。但是,我无法根据用户输入的内容从 Spotify 获取搜索结果,因为它不包含在我正在使用的教程中。我已经尝试根据提供给我的“获取用户配置文件”代码对搜索代码进行逆向工程,以创建对项目请求的搜索。
我现在想在文本框中输入一首歌曲,并将下面的结果返回到一个段落/div中
spotify.js
/**
* Axios global request headers
* https://github.com/axios/axios#global-axios-defaults
*/
axios.defaults.baseURL = 'https://api.spotify.com/v1';
axios.defaults.headers['Authorization'] = `Bearer ${access_token}`;
axios.defaults.headers['Content-Type'] = 'application/json';
/**
* Get Current User's Profile (works fine)
* https://developer.spotify.com/documentation/web-api/reference/#endpoint-get-current-users-profile
* @returns {Promise}
*/
export const getCurrentUserProfile = () => axios.get('/me');
/**
* Search for an Item (does not work :()
* https://developer.spotify.com/documentation/web-api/reference/search
* @returns {Promise}
*/
export const getSearch = (query, type) => axios.get(`/search?q=${query}&type=${type}`); //code I added
home.js
import { useState, useEffect } from 'react';
import { catchErrors } from '../../utils';
import { getCurrentUserProfile } from '../../spotify';
import { getSearch} from '../../spotify';
import axios from 'axios';
import './home.scss';
const Home = () => {
const [profile, setProfile] = useState(null);
const [search, setSearch] = useState('');
useEffect(() => {
const fetchData = async () => {
const { data } = await getCurrentUserProfile();
setProfile(data);
const { searchData } = await getSearch(); // code I added
setSearch(searchData); // code I added
};
catchErrors(fetchData());
}, []);
const onSubmit = (e) => { // function I added
e.preventDefault();
console.log(search);
axios.getSearch(search)
}
return (
<>
<div className = "main">
<h1>Welcome To (website title)</h1>
<p>To start making you a playlist, please enter a song below.</p>
<div className ="songInputDiv"><input className='songInput' type = "text" placeholder = "Enter a song here" onChange = {this.onSubmit}/></div>
<div><p>{search.tracks}</p></div>
</div>
</>
)
};
export default Home;