【问题标题】:Express.js; use route variables on a global scale快递.js;在全球范围内使用路由变量
【发布时间】:2021-09-12 03:06:42
【问题描述】:

我正在尝试将 Spotify API 与我的 express.js 服务器一起使用,并且需要从 URL 参数访问授权代码。我在我在 spotify 仪表板中指定的回调路由中使用let code = req.query.code 提取了这个值。然后我需要将其传递给 POST 请求(我正在使用请求模块,因为 api 的文档使用 cURL 示例)。但是,我不能全局使用code 变量,并且想避免使用全局变量。我该如何做到这一点?

重申一下,我想使用这条路线的代码变量:

app.get("/auth/spotify/callback", (req, res) => {
    let code = req.query.code;
    res.send({
      "code": code
    })
})

在此选项中 JSON:

var options = {
    'method': 'POST',
    'url': 'https://accounts.spotify.com/api/token',
    'headers': {
      'Authorization': 'Basic MmV...WU=',
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    form: {
      'grant_type': 'authorization_code',
      'code': code,
      'redirect_uri': 'http://localhost:5000/auth/spotify/callback'
    }
};

然后在此请求调用中使用:

request(options, function (error, response) {
    if (error) throw new Error(error);
    console.log(response.body);

每当我运行服务器时,它都会崩溃并指向选项 JSON 中使用的代码实例,声称它没有定义。这可能是一个简单的 JavaScript 问题,但我仍在学习后端实现。

这是错误:

C:\Users\Finn\Documents\Web\Projects\spotify application\server.js:30
      'code': code,
              ^

ReferenceError: code is not defined
    at Object.<anonymous> (C:\Users\Finn\Documents\Web\Projects\spotify application\server.js:30:15)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

server.js:

// ===server.js===
// MODULES
const request = require("request")
const express = require("express");
const app = new express();

// Auth vars
const [clientID, clientSecret, callbackURL] = ["2e...35", "5b...ae", "http%3A%2F%2Flocalhost%3A5000%2Fauth%2Fspotify%2Fcallback"]

// redirects to spotify to get code
app.get("/auth/spotify", (req, res) => {
    // takes to auth and then redirects to localhost:5000/auth/spotify/callback
    res.redirect(`https://accounts.spotify.com/authorize?client_id=${clientID}&response_type=code&redirect_uri=${callbackURL}&scope=user-top-read`)
})

// saves code in variable
app.get("/auth/spotify/callback", (req, res) => {
    let code = req.query.code;
    res.send({ "code": code })
})

var options = {
    'method': 'POST',
    'url': 'https://accounts.spotify.com/api/token',
    'headers': {
      'Authorization': 'Basic Basic MmV...WU=',
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    form: {
      'grant_type': 'authorization_code',
      'code': code,
      'redirect_uri': 'http://localhost:5000/auth/spotify/callback'
    }
};

// performs post request to receive access_token and refresh_token
request(options, function (error, response) {
    if (error) throw new Error(error);
    console.log(response.body);
});

// sets port variable
const PORT = process.env.PORT || 5000;

// start server function
app.listen(PORT, () => {
    console.log(`app is listening on port ${PORT}`);
});

感谢您的帮助。

【问题讨论】:

  • options 的范围在哪里?
  • 对不起,是的,我应该指定的。选项在全局范围内,在任何功能之外。以后有机会我会发布整个 server.js。
  • @code 添加了错误和完整的 server.js 文件
  • 在用户转到/auth/spotify/callback 之后,您是否要发送request?因为目前,一旦你运行你的节点应用程序,你就会发送请求......我不相信你是这个意思?
  • 是的,这正是我想要做的。我应该将它嵌套在/auth/spotify/callback 路由中吗?我试试看。

标签: javascript node.js express routes spotify


【解决方案1】:

您可以使用code 作为参数调用request 的函数:

function whateverName(code) {
  var options = {
    'method': 'POST',
    'url': 'https://accounts.spotify.com/api/token',
    'headers': {
      'Authorization': 'Basic Basic MmV...WU=',
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    form: {
      'grant_type': 'authorization_code',
      'code': code,
      'redirect_uri': 'http://localhost:5000/auth/spotify/callback'
    }
  };
  request(options, function (error, response) {
    if (error) throw new Error(error);
    console.log(response.body);
  });
}

app.get("/auth/spotify/callback", (req, res) => {
  let code = req.query.code;
  whateverName(code); // Sent!
  res.send({
    "code": code
  });
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-07
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    相关资源
    最近更新 更多