-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
85 lines (70 loc) · 2.03 KB
/
index.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const axios = require('axios');
const cors = require('cors');
const express = require('express');
const path = require('path');
const qs = require('qs');
require('dotenv').config()
const port = process.env.PORT || 8888;
const scope = process.env.SCOPE;
const client_id = process.env.CLIENT_ID;
const client_secret = process.env.CLIENT_SECRET;
const redirect_uri = process.env.REDIRECT_URI;
// Just to save authorization variables
const params = {};
const app = express();
app
.use(express.static(path.join(__dirname, 'client/build')))
.use(cors());
app.get('/login', (req, res) => {
res.redirect('https://accounts.spotify.com/authorize?' +
qs.stringify({
response_type: 'code',
client_id,
scope,
redirect_uri
}));
});
app.get('/callback', (req, res) => {
const code = req.query.code || null;
const payload = {
code,
redirect_uri,
grant_type: 'authorization_code'
};
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
}
};
axios.post('https://accounts.spotify.com/api/token', qs.stringify(payload), config)
.then(response => {
// console.log(res);
params.access_token = response.data.access_token;
params.refresh_token = response.data.refresh_token;
res.redirect('/profile');
})
.catch(err => {
console.error(err);
});
});
app.get('/api/top/artists', (req, res) => {
const time_range = req.query.time_range || null;
const target_url = 'https://api.spotify.com/v1/me/top/artists' + (time_range? '?time_range='+time_range : '');
axios.get(target_url, {
headers: {
'Authorization': 'Bearer ' + params.access_token
}
})
.then(response => {
res.json(response.data);
})
.catch(err => {
res.send(err);
});
});
app.get('*', (req,res) =>{
res.sendFile(path.join(__dirname+'/client/build/index.html'));
});
app.listen(port);
console.log('App is listening on port ' + port);