-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
56 lines (49 loc) · 1.51 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
const clientId = '';
const clientSecret = '';
let accessToken = '';
const getToken = async () => {
try {
const response = await axios.post('https://accounts.spotify.com/api/token', 'grant_type=client_credentials', {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`,
},
});
accessToken = response.data.access_token;
console.log('Access token:', accessToken);
} catch (error) {
console.error('Error fetching access token:', error);
}
};
// Refresh the token every hour
setInterval(getToken, 3600 * 1000);
getToken();
app.get('/search', async (req, res) => {
const { query } = req.query;
try {
console.log(`Searching for artist: ${query}`);
const response = await axios.get(`https://api.spotify.com/v1/search?q=${query}&type=artist`, {
headers: {
'Authorization': `Bearer ${accessToken}`,
},
});
console.log('Search response:', response.data);
res.json(response.data);
} catch (error) {
console.error('Error searching for artist:', error);
res.status(400).json({ error: error.message });
}
});
app.get('/token', (req, res) => {
res.json({ accessToken });
});
const PORT = 4000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});