繁体   English   中英

为什么我收到错误“'request' is not defined”?

[英]Why am I getting the error "'request' is not defined"?

我正在尝试使用 Spotify API 创建一个应用程序,但似乎无法使其正常工作。 我得到的错误是“请求”未定义,我也用 JQuery 替换了它,但这也不起作用。 谁能告诉我为什么我可能会收到该错误以及如何解决它? 我应该在 cmd 中的 node.js 中运行它吗?

var client_id = '?';
var client_secret = '?';

var authOptions = {
  url: 'https://accounts.spotify.com/api/token',
  headers: {
    'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
  },
  form: {
    grant_type: 'client_credentials'
  },
  json: true
};

request.post(authOptions, function(error, response, body) {
  if (!error && response.statusCode === 200) {
    var token = body.access_token;
  }
  else {
    console.log(JSON.stringify(error))
}
});

spotify 文档已过时,因为request弃用,不应再使用。
相反,您可以使用内置的 Node.js 库发出请求,如文档中所述。

它应该与node.js一起运行,即node <filename>

const https = require('https')

const client_id = 'CLIENT_ID'
const client_secret = 'CLIENT_SECRET'

const reqBody = JSON.stringify({
  grant_type: 'client_credentials'
})

const authOptions = {
  hostname: 'accounts.spotify.com',
  port: 443,
  path: '/api/token',
  method: 'POST',
  headers: {
    'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64')),
    'Content-Type': 'application/json',
    'Content-Length': reqBody.length
  }
}

const req = https.request(authOptions, res => {
  console.log(`statusCode: ${res.statusCode}`)

  res.on('data', d => {
    process.stdout.write(d)
  })
})

req.write(reqBody);
req.end();

暂无
暂无

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

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