NodeJS 尝试命中后路由时出现连接拒绝错误

wqsoz72f  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(128)

我试图在我的音乐播放器项目中使用Spotify API,每次我登录并在控制台中重定向到我的/spotfylogin路由时,它都会显示POST http://localhost:3001/spotifylogin net::ERR_CONNECTION_REFUSED
error in console
这是我的服务器js

// ==== [Cors] ====
app.use(cors());
const server = http.createServer(app);

//==== [Spotify] ====

app.use(bodyParser.json());

app.post("/spotifylogin", (req, res) => {
  const spotifyApi = new SpotifyWebApi({
    redirectUri: "http://localhost:3000/",
    clientId: "d67a6de2b2f045539acfef33cdff8840",
    clientSecret: "bd98e8446154499ab7eef56762cd16f2",
  });

  spotifyApi
    .authorizationCodeGrant(code)
    .then((data) => {
      res.json({
        accessToken: data.body.access_token,
        refreshToken: data.body.refresh_token,
        expiresIn: data.body.expires_in,
      });
    })
    .catch((err) => {
      console.log(err);
      res.sendStatus(400);
    });

  app.listen(3001);
});

字符串
这是我的auth jsx

import { useState, useEffect } from "react";
import axios from "axios";

export default function spotifyAuth(code) {
  const [accessToken, setAccessToken] = useState();
  const [refreshToken, setRefreshToken] = useState();
  const [expiresIn, setExpiresIn] = useState();

  useEffect(() => {
    axios
      .post("http://localhost:3001/spotifylogin", { code })
      .then((res) => {
        console.log(res.data);
        setAccessToken(res.data.accessToken);
        setRefreshToken(res.data.refreshToken);
        setExpiresIn(res.data.expiresIn);
        window.history.pushStage({}, null, "/");
      })
      .catch((err) => {
        console.log(err);
      });
  }, [code]);
  return accessToken;
}


我曾试图搞乱与cors交叉起源,但没有任何工作,甚至尝试代理通过vite配置,这也没有工作,任何帮助是赞赏
(NOTE:我对编码还是相当陌生的)

vi4fp9gy

vi4fp9gy1#

这不是一个完整的解决方案,但我只是解决了服务器端的问题。你能继续走前面(vite和React部分)
server.js将新的子目录定位为“express”目录。
./express/server.js

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

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

CLIENT_ID = "your client ID"
CLIENT_SECRET = "your client secret"
PORT = 3000 // it is located in Spotify dashboard's Redirect URIs, my port is 3000 too
REDIRECT_URI = `http://localhost:${PORT}/spotifylogin` 

const spotifyApi = new SpotifyWebApi({
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
    redirectUri: REDIRECT_URI
})

SCOPE = [
    'user-read-private',
    'user-read-email',
    'user-library-read',
    'playlist-read-private',
    'playlist-modify-public',
    'playlist-modify-private'
]

app.get("/login", (request, response) => {
    const redirect_url = `https://accounts.spotify.com/authorize?response_type=code&client_id=${CLIENT_ID}&scope=${SCOPE}&state=123456&redirect_uri=${REDIRECT_URI}&prompt=consent`
    response.redirect(redirect_url);
})

app.get("/spotifylogin", async (request, response) => {
    const authorizationCode = request.query["code"]
    spotifyApi
        .authorizationCodeGrant(authorizationCode)
        .then((data) => {
            spotifyApi.setAccessToken(data.body['access_token'])
            spotifyApi.setRefreshToken(data.body['refresh_token']);
            tokenExpirationEpoch = new Date().getTime() / 1000 + data.body['expires_in'];
            response.send({
                access_token: data.body['access_token'],
                refresh_token: data.body['refresh_token'],
                'Retrieved token. It expires in ': Math.floor(tokenExpirationEpoch - new Date().getTime() / 1000) + ' seconds!'
            })
        })
})
app.get("/me", async (request, response) => {
    spotifyApi
        .getMe()
        .then((data) => {
            return response.send({me: data.body})
        })
})

app.get("/artist", async (request, response) => {
    const defaultArtistId = '19eLuQmk9aCobbVDHc6eek'
    const artistId = (request.query.artistId == null)?  defaultArtistId : request.query.artistId
    spotifyApi.getArtistRelatedArtists(artistId)
        .then((data) => {
            return response.send({ artist: data.body })
        })
})

app.get("/playlist", async (request, response) => {
    const defaultPlaylistId = '37i9dQZF1DX0tnKPLNG9Ld'
    const playlistId = (request.query.playlistId == null)?  defaultPlaylistId : request.query.playlistId
    spotifyApi.getPlaylist(playlistId)
        .then((data) => {
            return response.send({ playlist: data.body })
        })
})

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

字符串

前端

App.jsx

function App() {
  return (
    <Spotify />
  );
}


Spotify.jsx

import React from "react";

import { Container } from "react-bootstrap";

const SERVER_URL = "http://localhost:3000/login";
export default function Spotify() {
  return (
    <Container
      className="d-flex justify-content-center align-items-center"
      style={{ minHeight: "100vh" }}
    >
      <a className="btn btn-success btn-lg" href={SERVER_URL}>
        Login with Spotify
      </a>
    </Container>
  );
}


vite.config.js

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    port: 3005,
    open: true,
    proxy: {
      "/graphql": {
        target: "http://localhost:3001",
        changeOrigin: true,
        secure: false,
      },
    },
  },
});


步骤

1在express目录下安装依赖项

npm install spotify-web-api-node express cors

2在express目录下运行服务器

node server.js

3在src目录下运行客户端

npm run start

4在浏览器中按登录

5令牌将显示

同样,这不是整个解决方案,我只是演示了从前端和后端登录和显示令牌的调用,而不是返回到前端。

相关问题