繁体   English   中英

Spotify 请求授权错误 API

[英]Request authorization error in Spotify API

最奇怪的事情发生在我的 React 应用程序上。 我已将 Client Id 和 Client Secret 移动到环境变量中,并使用 dotenv 将它们加载到此文件中以创建授权请求

// Inject environment variables
import dotenv from 'dotenv';
dotenv.config();

const clientID = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;

// Request authorization
const authOptions = {
  url: "https://accounts.spotify.com/api/token",
  headers: {
    "Authorization":
      "Basic " +
      new Buffer.from(clientID + ":" + clientSecret).toString("base64"),
    "Content-Type": "application/x-www-form-urlencoded",
  },
  form: {
    grant_type: "client_credentials",
  },
  json: true,
};

export default authOptions;

但是我收到Failed to load resource: the server responded with a status of 400 ()错误:

{ error: "invalid_client", error_description: "Invalid client" }

奇怪的是,如果对客户端 ID 和密码进行硬编码,它就可以完美运行。

我什至在控制台中打印了环境变量并获得了正确的值,但是当我在授权 header 中使用它们时它停止工作。

有没有什么办法解决这一问题?

从我看到你所做的是在浏览器中不可用的反应中使用 env 变量。

只是一个旁注,也许你不应该在浏览器中加载秘密,因为那不是一个安全的环境。 而是使用 OAuth 策略来使用您的客户端 ID。 这是一个链接

将环境变量加载到您的应用程序。 您需要在它前面加上REACT_APP_ 这是一个链接

这是一个例子

.env

REACT_APP_CLIENT_ID=my-spotify-client-id

我有一次这个错误。 我重置了我的client_secret ,在.env文件中添加了新值,但忘记终止我的应用程序并再次运行它。 在我重新运行我的应用程序后,它起作用了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM