Axios Post错误 – Spotify API的连接被拒绝

huangapple go评论80阅读模式
英文:

Axios Post Error - Connection Refused for Spotify API

问题

I can provide a translation of the text you provided:

"非常感谢帮助我找出为什么我在我的 axios post 请求中收到错误的原因。我是第一次使用 API,并且也想知道如何最好地处理类似这样的错误。

请让我知道您是否需要其他任何帮助来解决这个问题。

尝试将 catch 处理注释掉以返回主页,按照 webdev simplified 的 Spotify 教程"

Please note that I've only translated the text and omitted the code sections as you requested. If you have any further questions or need assistance with this issue, please feel free to ask.

英文:

Would very much appreciate help figuring out why i am receiving an error in my axios post request. New to using APIs and would also love to know how I can best error handle things like this.

const express = require('express');
const spotifyWebApi = require('spotify-web-api-node');
const cors = require('cors');

const app = express();
const bodyParser = require('body-parser');
app.use(cors())
app.use(bodyParser.json())

app.post('/refresh', (req, res) => {
    const refreshToken = req.body.refreshToken;
    console.log(refreshToken)
    const spotifyApi = new spotifyWebApi({
        redirectUri: 'http://localhost:3000',
        clientId: '34203c820a8a49b783fb4588f1b241df',
        clientSecret: '9343f7f9db05463cbf2c1b9532b9137e',
        refreshToken,
    })

    spotifyApi.refreshAccessToken().then(
    (data) => {
        res.json({
            accessToken: data.body.access_token,
            expiresIn: data.body.expires_in,
        })

    }).catch(err => {
        console.log(err)
        res.sendStatus(400)

    }) 
});
       
app.post('/login', (req, res) => {
    const code = req.body.code;
    const spotifyApi = new spotifyWebApi({
        redirectUri: 'http://localhost:3000',
        clientId: '34203c820a8a49b783fb4588f1b241df',
        clientSecret: /
    })


    spotifyApi.authorizationCodeGrant(code).then(data => {
    res.json({
        accessToken: data.body.access_token,
        refreshToken: data.body.refresh_token,
        expiresIn: data.body.expires_in,
    })

    }).catch(()=> {
    res.sendStatus(400)
    })

});

app.listen(3001);

Please let me know if you need anything else to help me solve this problem.

Tried commenting out catch handle to home page,
following webdev simplified spotify tutorial

答案1

得分: 1

以下是翻译好的部分:

#1 不正确的地方有四个。

#1 你不需要使用 app.post,需要改成 app.get

POST API 调用将在 spotifyApi.refreshAccessToken()spotifyApi.authorizationCodeGrant() 中调用。

Express 只响应用户浏览器访问的 app.get()

axios 的 POST 与此问题无关。

#2 app.get("/callback") 将由 Spotify 服务器调用,你需要捕获 code 并将其转发给 spotifyApi.authorizationCodeGrant(code),这部分缺失了。

#3 你忘了将令牌设置给 spotifyApi。这有助于通过 refreshAccessToken() 获取下一个访问令牌。

// 保存访问令牌
spotifyApi.setAccessToken(data.body.access_token);

// 保存刷新令牌
spotifyApi.setRefreshToken(data.body.refresh_token);

#4 Express 回调端口和重定向端口号不匹配。

Express 使用 3001

app.listen(3001);

重定向 URI 使用 3000

http://localhost:3000

两者应该匹配

这个演示代码将可以工作

保存为 demo.js 文件名。

const SpotifyWebApi = require('spotify-web-api-node')
const express = require("express")
const cors = require("cors")

const app = express()
app.use(cors())

PORT = 3000

const scopes = ['user-read-private', 'user-read-email'] // 你需要添加一个作用域,它取决于你的 API 调用
const state = 'what-ever-your-state';

var spotifyApi = new SpotifyWebApi({
    clientId: 'your client ID',
    clientSecret: 'your client secret',
    redirectUri: `http://localhost:${PORT}/callback`    // my redirectURL is `localhost:3000/callback`
});

app.get("/login", (request, response) => {
    var authorizeURL = spotifyApi.createAuthorizeURL(scopes, state);
    response.redirect(authorizeURL);
})

app.get("/callback", async (request, response) => {
    const code = request.query["code"]
    spotifyApi.authorizationCodeGrant(code).then(data => {
        // 保存访问令牌
        spotifyApi.setAccessToken(data.body.access_token);

        // 保存刷新令牌
        spotifyApi.setRefreshToken(data.body.refresh_token);

        // 在浏览器中显示令牌
        return response.send(JSON.stringify({
            accessToken: data.body.access_token,
            refreshToken: data.body.refresh_token,
            expiresIn: data.body.expires_in,
        }));
    }).catch(() => {
        response.sendStatus(400)
    })
})

app.get("/refresh", async (request, response) => {
    spotifyApi.refreshAccessToken().then(data => {
        // 保存访问令牌
        spotifyApi.setAccessToken(data.body.access_token);

        // 在浏览器中显示令牌
        return response.send(JSON.stringify({
            accessToken: data.body.access_token,
            expiresIn: data.body.expires_in,
        }));
    }).catch(() => {
        response.sendStatus(400)
    })
})

app.listen(PORT, () => {
    console.log(`Listening on :${PORT}`)
})

安装依赖项

npm install spotify-web-api-node express cors

运行

node demo.js

登录

http://localhost:3000/login

它将显示一个访问令牌和一个刷新令牌。

通过刷新令牌 API 获取新的访问令牌

http://localhost:3000/refresh

演示结果

Spotify Web API Node

英文:

Four items are wrong.

#1 You don't need to serve app.post, it needs to change into app.get

The POST API call, will call inside spotifyApi.refreshAccessToken() and spotifyApi.authorizationCodeGrant()

The express just response app.get() for the user's browser access.

The axois POST is not related to this question.

#2 The app.get("/callback") will call by Spotify server, you needs to capture code and forward to the spotifyApi.authorizationCodeGrant(code), that part is missing

#3 You missed set tokens to the spotifyApi.
It helps to get the next access token by refreshAccessToken()

// save access token
spotifyApi.setAccessToken(data.body.access_token);
// save refresh token
spotifyApi.setRefreshToken(data.body.refresh_token);

#4 Miss match Express callback port and redirect port number.

Express use 3001

app.listen(3001);

Redirect URI use 3000

http://localhost:3000

Both should be a match

This demo code will work

Save as demo.js file name.

const SpotifyWebApi = require('spotify-web-api-node')
const express = require("express")
const cors = require("cors")

const app = express()
app.use(cors())

PORT = 3000

const scopes = ['user-read-private', 'user-read-email'] // you need to add a scope, it depends on your API call
const state = 'what-ever-your-state'

var spotifyApi = new SpotifyWebApi({
    clientId: 'your client ID',
    clientSecret: 'your client secret',
    redirectUri: `http://localhost:${PORT}/callback`    // my redirectURL is `localhost:3000/callback`
});

app.get("/login", (request, response) => {
    var authorizeURL = spotifyApi.createAuthorizeURL(scopes, state);
    response.redirect(authorizeURL);
})

app.get("/callback", async (request, response) => {
    const code = request.query["code"]
    spotifyApi.authorizationCodeGrant(code).then(data => {
        // save access token
        spotifyApi.setAccessToken(data.body.access_token);

        // save refresh token
        spotifyApi.setRefreshToken(data.body.refresh_token);

        // show tokens in browser
        return response.send(JSON.stringify({
            accessToken: data.body.access_token,
            refreshToken: data.body.refresh_token,
            expiresIn: data.body.expires_in,
        }));
    }).catch(() => {
        response.sendStatus(400)
    })
})

app.get("/refresh", async (request, response) => {
    spotifyApi.refreshAccessToken().then(data => {
        // save access token
        spotifyApi.setAccessToken(data.body.access_token);

        // show token in browser
        return response.send(JSON.stringify({
            accessToken: data.body.access_token,
            expiresIn: data.body.expires_in,
        }));
    }).catch(() => {
        response.sendStatus(400)
    })
})

app.listen(PORT, () => {
    console.log(`Listening on :${PORT}`)
})

Install dependencies

npm install spotify-web-api-node express cors

Run it

node demo.js

Log in

http://localhost:3000/login

It will display an access token and a refresh token.

Axios Post错误 – Spotify API的连接被拒绝

Get New Access Token by refreshing the token API

http://localhost:3000/refresh

Axios Post错误 – Spotify API的连接被拒绝

Demo Result

Axios Post错误 – Spotify API的连接被拒绝

Reference

Spotify Web API Node

huangapple
  • 本文由 发表于 2023年6月29日 23:44:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76582636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定