我是javascript
的新手,正在尝试使用某种方法创建一个简单的类,但是遇到了问题,无法弄清楚自己在做什么。
var SpotifyWebApi = require('spotify-web-api-node');
const my_client_id = "xxx";
const my_secret = "xxx";
class Spotify {
constructor() {
this.spotifyApi = new SpotifyWebApi({
redirectUri: 'http://localhost:8081/spotifyCallback',
clientId: my_client_id,
clientSecret: my_secret
});
}
connect() {
console.log(this.spotifyApi.redirectUri);
return spotifyApi.createAuthorizeURL('teststate', ['user-read-private', 'user-read-email']);
};
}
在这里,当我尝试登录控制台spotifyApi.redirectUri时,我不确定(尝试使用和不使用this关键字)。
答案 0 :(得分:3)
这是因为实例化它的lib(https://github.com/thelinmichael/spotify-web-api-node)使用redirectUri
作为选项,但没有将其公开为属性。
如果您仍然需要它,请将redirectUri
放在类属性中,如下所示:
const SpotifyWebApi = require('spotify-web-api-node');
class Spotify {
constructor(my_client_id, my_secret) {
this.redirectUri = 'http://localhost:8081/spotifyCallback';
this.spotifyApi = new SpotifyWebApi({
redirectUri: this.redirectUri,
clientId: my_client_id,
clientSecret: my_secret
});
}
connect() {
console.log(this.redirectUri);
return this.spotifyApi.createAuthorizeURL('teststate', ['user-read-private', 'user-read-email']);
};
}
const my_client_id = "xxx";
const my_secret = "xxx";
// Now you can instantiate your class with this :
const spotify = new Spotify(my_client_id, my_secret);
const yourToken = spotify.connect();
我以一些好的做法(使用this
添加构造函数参数,...)来编辑答案
答案 1 :(得分:2)
您访问对象的方式不正确。看下面的代码和输出。
const SpotifyWebApi = require('spotify-web-api-node');
const my_client_id = "xxx";
const my_secret = 'xxx';
const redirectUri='http://localhost:8081/spotifyCallback';
class Spotify {
constructor(my_client_id, my_secret, redirectUri) {
this.spotifyApi = new SpotifyWebApi({
clientId: my_client_id,
clientSecret: my_secret,
redirectUri: redirectUri
});
}
connect() {
console.log(JSON.stringify(spotify.spotifyApi._credentials,null,4));
console.log(this.spotifyApi._credentials.redirectUri);
return this.spotifyApi.createAuthorizeURL(['user-read-private', 'user-read-email'],'teststate');
};
}
//Instantiate
const spotify = new Spotify(my_client_id, my_secret ,redirectUri);
const connectObject = spotify.connect();
输出:
{
"clientId": "xxx",
"clientSecret": "xxx",
"redirectUri": "http://localhost:8081/spotifyCallback"
}
http://localhost:8081/spotifyCallback
您还没有为createAuthorizeURL
传递正确的参数。看看前面的signautre和spotify-web-api-node