【问题标题】:axios GET request doesn't return any data (VueJS & NodeJS)axios GET 请求不返回任何数据(VueJS 和 NodeJS)
【发布时间】: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 }} 部分。需要注意的几点:

  1. 请求正确到达后端,因为就像我提到的,预期的结果会打印在终端中。
  2. 如果我取消注释 // .catch(error =&gt; alert(error)) 部分,我会收到一条警告说 "Error: Network Error"
  3. 我认为问题出在 .then(response =&gt; (this.info = response.body.items[0])) 部分,因为我已经在后端“编辑”了 JSON 部分,但 .then(response =&gt;(this.info = response)).then(response =&gt;(this.info = response.body)) 都没有工作。
  4. 基本上,对info 的分配不会发生,因为如果我将.catch 更改为.catch(alert(this.info)),我会在警报中得到null
  5. 我也试过thismounted 看起来像这样:
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 =&gt; console.error(error)) 后,我在 Inspect Element 中得到以下信息: console outputthis Network output

【问题讨论】:

  • 对于 axios,它将是 response.data.items,但 Network Error 在此之前。使用console.error 记录错误并检查网络选项卡以获取失败的响应并将该信息添加到问题中。

标签: node.js json vue.js axios


【解决方案1】:

这是部分答案,因为我最终改变了很多东西。 正如您在我包含的控制台输出照片中看到的那样,我收到了一个错误

跨域请求被阻止 (...)

This was a cors error 由于服务器在不同的本地主机中运行(前端为 8080,后端为 8888)。我通过在我的app.js 文件中包含以下内容解决了这个问题,因为我也在使用express

var cors = require('cors');
app.use(cors());

另外,前端请求中的mounted 部分应该是response.data

【讨论】:

    猜你喜欢
    • 2020-08-09
    • 2019-09-07
    • 2021-08-08
    • 2021-02-03
    • 2019-10-10
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多