首页 > 解决方案 > Firebase Cloud Functions Express 应用退货声明

问题描述

我目前正在构建一个使用 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);

标签: firebasegoogle-cloud-functions

解决方案


正如 Doug 在此问题的评论部分中提到的,您的 return 声明似乎不在适当的部分。它嵌套在两个回调函数的深处,它们返回顶级函数的数据。如果您希望此代码工作并返回您要求它返回的变量,请考虑将此 return 语句移动到在您的代码中生成最终响应的函数中。


推荐阅读