【问题标题】:Why axios.get gets null while the URL works fine when visited in browser?为什么在浏览器中访问 URL 时 axios.get 为空,而 URL 工作正常?
【发布时间】:2020-08-02 02:53:55
【问题描述】:
import axios from 'axios';

const URL = 'http://localhost:5000/api/posts/';

class PostService {
    static getPosts() {
        return new Promise( (resolve, reject) => {
            try {
                const res = axios.get(URL);
                const data = res.data;
                resolve(
                    data.map(post => ({
                        ...post,
                        createdAt: new Date(post.createdAt)
                    }))
                )
            }
            catch (e) {
                reject(e);
            }
        });
    }

运行时出现“TypeError: Cannot read property 'map' of undefined”的错误。 原来变量data 为空。 但是,当我在浏览器中访问 URL 时,数据完美显示如下: screenshot of data

谁能告诉我为什么? 谢谢~

【问题讨论】:

  • 我不确定,但您应该等待axios.get 与async axios.get 一起解决。也许您必须在getPosts 前加上await getPosts。否则代码看起来不错,更多阅读:javascript.info/async-await
  • 致 Marc:你是对的,这就是问题所在。我应该等待 axios.get。谢谢~但是我不能在getPosts前加上await,这是一个语法错误......也许Abraham Labkovsky的方法是解决它的唯一方法?

标签: javascript vue.js axios


【解决方案1】:

在引用它之前,您无需等待 .get 函数调用解析。 在异步函数中,您可以等待它,但在承诺中,您必须将异步任务放入 .then()

编辑:也许这不是很清楚,

试试:

import axios from 'axios';

const URL = 'http://localhost:5000/api/posts/';

class PostService {
static getPosts() {
    return new Promise( (resolve, reject) => {
        axios.get(URL)
        .then(res => resolve(res.data.map(post => ({
                    ...post,
                    createdAt: new Date(post.createdAt)
                }))))
        .catch(reject)
    });
}

【讨论】:

    猜你喜欢
    • 2014-12-10
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 2021-07-30
    相关资源
    最近更新 更多