【问题标题】:How do you make this curl request in node你如何在节点中发出这个 curl 请求
【发布时间】:2018-04-17 23:56:14
【问题描述】:

对 spotify API 的 curl 请求运行良好

curl -X "POST" -H "Authorization: Basic <my-key-here>" -d grant_type=client_credentials https://accounts.spotify.com/api/token

我正在尝试在节点中执行此操作,但它不起作用并返回 400 错误请求。这是我的代码。我做错了什么?

function AuthRequest(key) {

  const req_body_params = JSON.stringify({
    grant_type: "client_credentials"
  })

  const base64_enc = new Buffer(key).toString("base64")

  const options = {
    host: "accounts.spotify.com",
    port: 443,
    path: "api/token",
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Basic ${base64_enc}`
    }
  }

  const req = https.request(options, function (res) {
    res.on('data', function (data) {
      alert("success: " + data)
    })
  })

  req.on('error', function (err) {
    alert("error: " + err)
  })

  req.write(req_body_params)
  req.end()

}

我正在尝试使用此处解释的客户端凭据方法:https://developer.spotify.com/web-api/authorization-guide/

【问题讨论】:

  • 您遇到的错误是什么?
  • 400 错误请求
  • 您缺少必要的参数,例如代码和 redirect_uri
  • 您的 req 正文参数应该是您的选项对象的一部分,它们应该在查询参数语法中指定。将body: 'grant_type=client_credentials' 添加到您的选项对象并重试请求并注释掉req.write
  • 没有帮助。一样的回应。还尝试了application/x-www-form-urlencoded,就像@AngYC 建议的那样。没用。

标签: node.js curl https request


【解决方案1】:

请求应该是application/x-www-form-urlencoded而不是JSON,它应该是const req_body_params = "grant_type=client_credentials",标题为"Content-Type": "application/x-www-form-urlencoded"

function AuthRequest(key) {
    const req_body_params = "grant_type=client_credentials";
    const base64_enc = new Buffer(key).toString("base64");

    const options = {
        host: "accounts.spotify.com",
        port: 443,
        path: "/api/token",
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": `Basic ${base64_enc}`
        }
    };

    const req = https.request(options, function(res) {
        res.on('data', function(data) {
            alert("success: " + data)
        })
    });

    req.on('error', function(err) {
        alert("error: " + err)
    });

    req.write(req_body_params);
    req.end();
}

【讨论】:

  • 我真的希望这是答案,但我也收到 400 Bad Request 这个代码。
  • 我认为您错过了路径的前导斜杠?
  • 哦,太好了!谢谢!
【解决方案2】:

因为令牌过期可以动态请求它们,所以我创建了一个输出令牌作为承诺的方法,然后你可以在你的请求中消费。

const axios = require('axios')

const client_id = process.env.SPOTIFY_CLIENT_ID;
const client_secret = process.env.SPOTIFY_CLIENT_SECRET;

function getToken( ) {
    return axios({
        url: 'https://accounts.spotify.com/api/token',
        method: 'post',
        params: {
            grant_type: 'client_credentials'
        },
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        auth: {
            username: client_id,
            password: client_secret
        }
   })
}


async function getSpotifyData( endpoint ){
    const tokenData = await getToken( );
    const token = tokenData.data.access_token;
    axios({
        url: `https://api.spotify.com/v1/${endpoint}`,
        method: 'get',
        headers: {
            'Authorization': 'Bearer ' + token
        }
    }).then( response =>  {
        console.log( response.data );
        return response.data;
    }).catch( error =>  {
        throw new Error(error);
    });
}
getSpotifyData( 'browse/new-releases' );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    相关资源
    最近更新 更多