【发布时间】:2018-11-27 00:55:10
【问题描述】:
我目前正在构建一个使用 Spotify API 的 Firebase Cloud 函数。
现在我知道这段代码有效,因为我在创建 Express 应用程序之前也使用过它。
但从那以后,我似乎无法让我的云函数返回任何东西......
我真的不明白我做错了什么。
const app = express();
app.use(cors({ origin: true }));
app.get("/", (req, res) => res.send("No track specified"));
app.get("/:track", (req, res) => res.send(getTrack(req.params.track)));
function getTrack(track) {
// Set up Auth options
console.log(track);
const spotify_auth_options = {
url: "https://accounts.spotify.com/api/token",
headers: {
Authorization:
"Basic " +
new Buffer(spotify_client_id + ":" + spotify_client_secret).toString(
"base64"
)
},
form: {
grant_type: "client_credentials"
},
json: true
};
request.post(spotify_auth_options, function(error, response, body) {
if (!error && response.statusCode === 200) {
console.log("No error");
// use the access token to access the Spotify Web API
var token = body.access_token;
var options = {
url: "https://api.spotify.com/v1/search?q=" + track,
headers: {
Authorization: "Bearer " + token
},
json: true
};
request.get(options, function(error, response, body) {
console.log(body.tracks);
return body.tracks;
});
}
});
}
exports.searchTrack = functions.https.onRequest(app);
【问题讨论】:
-
您正在尝试使用深度嵌套在两个回调中的
return关键字从有效异步的顶级函数返回数据。这绝对行不通。考虑更有效地使用 Promise,或者将 Response 对象传递给生成最终响应的函数,然后从那里调用它。 -
道格,这看起来像是解决方案。您介意将其作为答案,以便其他人可以投票吗?
标签: firebase google-cloud-functions