在 Node.js 中收到来自 POST 请求的 JSON 响应

Receive JSON response from POST request in Node.js

我正在尝试授权在 NodeJS 中使用 Spotify。这是我的代码:

app.get('/auth', function(req, res){
  if(req.query.error){
    res.redirect('/error');
  };
  var resdata;
  const data = querystring.stringify({
    'grant_type':'authorization_code',
    'code': req.query.code,
    'redirect_uri': 'https://<MYURL>/auth',
    'client_id': process.env.ID,
    'client_secret': process.env.SECRET
  })
  const options = {
    hostname: 'accounts.spotify.com',
    port: 443,
    path: '/api/token',
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': data.length
    }
  }

 const authreq = https.request(options, authres => {

   authres.on('data', d => {
     resdata += d;
   })

   authres.on('end', d => {
     res.send(resdata);
   })
 })

当我发出请求时,我得到了这样的回应:

undefined{\"access_token\":\"<TOKEN>\",\"token_type\":\"Bearer\",\"expires_in\":3600,\"refresh_token\":\"<TOKEN>\",\"scope\":\"playlist-read-private user-modify-playback-state\"}

如何将其变成 JSON?

我想在纯 NodeJS 中执行此操作,如果可能的话不使用任何模块。

你可以使用 JSON.parse(result.slice(9))

但可能还有更好的方法。

像这样将 resdata 分配给空字符串,而不是保持未定义状态。

var resdata = '';

最后听众将其更改为

authres.on('end', d => {
     res.send(JSON.parse(resdata));
   })