首页 > 解决方案 > 为什么在浏览器中访问 URL 时 axios.get 为空,而 URL 工作正常?

问题描述

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 时,数据完美显示如下: 数据截图

有人能告诉我为什么吗?谢谢~

标签: javascriptvue.jsaxios

解决方案


在引用它之前,您无需等待 .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)
    });
}

推荐阅读