我正在尝试构建一个Spotify Web应用程序。当我在Albums.js中发出get请求时,server.js文件中的data.body.items显示正确的数据,但是当我在Albums.js中使用console.log()打印其响应时,它是未定义的。 我想使用响应中的数据。我该如何解决该问题?
Albums.js
import React from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";
const Albums = () => {
const { id } = useParams();
const handleClick = () => {
axios
.get(`http://localhost:4000/albums/${encodeURIComponent(id)}`, {
params: {
id: id,
},
})
.then((res) => {
console.log(`Returned album data from the server: ${res}`);
return res.data;
})
.catch((err) => console.log(err));
};
return (
<>
<div className="container" style={{ color: "white" }}>
{`${id}'s albums`}
{console.log(handleClick())}
</div>
</>
);
};
export default Albums;
server.js
const express = require("express");
const SpotifyWebApi = require("spotify-web-api-node");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const port = 4000 || process.env.PORT;
require("dotenv").config();
app.use(express.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
// Create the api object with the credentials
var spotifyApi = new SpotifyWebApi({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
});
// Retrieve an access token.
spotifyApi.clientCredentialsGrant().then(
function (data) {
console.log("The access token expires in " + data.body["expires_in"]);
// Save the access token so that it's used in future calls
spotifyApi.setAccessToken(data.body["access_token"]);
},
function (err) {
console.log("Something went wrong when retrieving an access token", err);
}
);
app.post("/search_result", (req, res) => {
spotifyApi
.searchArtists(req.body.keyword)
.then(function (data) {
let search_res = data.body.artists.items;
res.json(search_res);
res.end();
})
.catch((err) => {
console.log(err);
res.status(500).send(err);
});
});
app.get("/albums/:id", (req, res) => {
console.log(req.params.id);
spotifyApi.getArtistAlbums(req.params.id).then(function (data) {
console.log(data.body.items);
res.json(data.body.items);
res.end();
});
});
app.listen(port, () => console.log(`It's running on port ${port}`));