Post请求 net::ERR_CONNECTION_REFUSED
Post请求 net::ERR_CONNECTION_REFUSED
我正在构建一个使用React/Redux/Node的应用程序,该应用程序将Spotify的API与授权码流集成在一起。这是一个使用React-Router的单页应用程序,有三个路由:登录、时间轴和结果。当从时间轴转到结果时,我收到以下错误:
POST http://localhost:3001/login net::ERR_CONNECTION_REFUSED
这是Github仓库的链接:链接。
这是打开Chrome DevTools时错误的视频:链接。
useAuth.jsx(自定义hook)
import { useState, useEffect } from 'react' import axios from 'axios' const useAuth = (code) => { const [accessToken, setAccessToken] = useState() useEffect(() => { axios.post('http://localhost:3001/login', { code, }).then(res => { setAccessToken(res.data.accessToken) window.history.pushState({}, null, '/') }).catch((err) => { console.log(err) }) }, [code]) return accessToken } export default useAuth
server.js
require('dotenv').config() const express = require('express'); const SpotifyWebApi = require('spotify-web-api-node'); const cors = require('cors') const bodyParser = require('body-parser') const app = express(); app.use(cors()) app.use(bodyParser.json()) app.post('/login', (req, res) => { const code = req.body.code const spotifyApi = new SpotifyWebApi({ redirectUri: process.env.REDIRECT_URI, clientId: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, }) 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)
App.js
import {useState, useEffect} from 'react' import { Login } from './Login' import { Timeline } from './Timeline' import { Results } from './Results' import { BrowserRouter as Router, Routes, Route } from 'react-router-dom' import './App.css' const code = new URLSearchParams(window.location.search).get('code'); const App = () => { const [composers, setComposers] = useState([]); useEffect(() => { const fetchComposers = async () => { const response = await fetch('composers.json'); const data = await response.json(); const listofComposers = data.composers.map((composer) => composer) setComposers(listofComposers); } fetchComposers(); }, []); return (); } export default App; } /> } /> } />
Results.jsx
export const Results = ({ code }) => { const accessToken = useAuth(code) console.log(accessToken)
当我使用console.log(accessToken)时,它返回undefined。