【发布时间】:2021-03-25 13:28:29
【问题描述】:
我正在尝试从前端 (vueJS) 到后端 (nodeJS) 进行 API 调用。这是我在后端处理原始 api 请求的代码:
app.route('/myplaylists')
.get(function(req, res) {
spotifyApi.getUserPlaylists({ limit: 1, offset: 1 })
.then(function(data) {
res.send('Success! Playlists fetched.');
const tbr = JSON.stringify(data.body.items[0], null, 4);
console.log('Retrieved playlists', tbr);
});
},function(err) {
console.log('Something went wrong!', err);
});
});
如您所见,我正在使用this 包装器,但我认为这并不重要。这部分代码工作正常,因为我确实在终端中打印了所需的结果,即:
{
"collaborative": false,
"description": "The songs you loved most this year, all wrapped up.",
"external_urls": {
"spotify": "https://open.spotify.com/playlist/37i9dQZF1ELWjgC8Aiv78C"
},
"href": "https://api.spotify.com/v1/playlists/37i9dQZF1ELWjgC8Aiv78C",
"id": "37i9dQZF1ELWjgC8Aiv78C",
"images": [
{
"height": null,
"url": "https://lineup-images.scdn.co/wrapped-2020-top100_LARGE-en.jpg",
"width": null
}
],
"name": "Your Top Songs 2020",
"owner": {
"display_name": "Spotify",
"external_urls": {
"spotify": "https://open.spotify.com/user/spotify"
},
"href": "https://api.spotify.com/v1/users/spotify",
"id": "spotify",
"type": "user",
"uri": "spotify:user:spotify"
},
"primary_color": null,
"public": false,
"snapshot_id": "MjY3NzQ1NzIsMDAwMDAwMDA1NTUxYmQyZGVhMzAwODYxYzQ5ZmMwMDRhMmUyMDRkOQ==",
"tracks": {
"href": "https://api.spotify.com/v1/playlists/37i9dQZF1ELWjgC8Aiv78C/tracks",
"total": 100
},
"type": "playlist",
"uri": "spotify:playlist:37i9dQZF1ELWjgC8Aiv78C"
}
这是我制作 api req 的 vue 组件:
<template>
<div id="thisisatest">
<h1>This is a page to test api calls.</h1>
<h2>
The json result should be displayed here:
</h2>
<p>{{ info }}</p>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'About',
data () {
return {
info: null
}
},
mounted () {
axios
this.$http
.get('http://localhost:8888/myplaylists')
.then(response => (this.info = response.body.items[0]))
// .catch(error => alert(error))
},
};
</script>
但不显示{{ info }} 部分。需要注意的几点:
- 请求正确到达后端,因为就像我提到的,预期的结果会打印在终端中。
- 如果我取消注释
// .catch(error => alert(error))部分,我会收到一条警告说"Error: Network Error" - 我认为问题出在
.then(response => (this.info = response.body.items[0]))部分,因为我已经在后端“编辑”了 JSON 部分,但.then(response =>(this.info = response))和.then(response =>(this.info = response.body))都没有工作。 - 基本上,对
info的分配不会发生,因为如果我将.catch更改为.catch(alert(this.info)),我会在警报中得到null。 - 我也试过this。
mounted看起来像这样:
mounted () {
var temp = this.info;
axios
this.$http
.get('http://localhost:8888/myplaylists')
.then(response => (temp = response.body.items[0]))
然后我收到35:13 error 'temp' is assigned a value but never used no-unused-vars 错误。
编辑:针对马特的评论,首先response.data.items 也不起作用。然后,在将 .catch 更改为 .catch(error => console.error(error)) 后,我在 Inspect Element 中得到以下信息:
console output 和 this Network output
【问题讨论】:
-
对于 axios,它将是
response.data.items,但Network Error在此之前。使用console.error记录错误并检查网络选项卡以获取失败的响应并将该信息添加到问题中。