【问题标题】:Axios is returning undefinedAxios 返回未定义
【发布时间】:2021-12-29 03:41:17
【问题描述】:

当我向 Postman 请求时,我的 API 正在返回正确的数据。甚至 API 也可以从 React 正确调用,我在控制器内部使用 console.log 检查,但我总是收到 undefined 响应。我不确定是什么错误。

const submit = async (e: SyntheticEvent) => {
    e.preventDefault();

    const response = await axios
        .get('certificates', {
            params: { sponser },
        })
        .then((res) => {
            console.log(response); //undefined
            alert(res.status);  //200
            alert(res); //[object Object]
        });
};

你能帮我做同样的事情吗?

【问题讨论】:

  • 你是说console.log(response);记录undefined吗?还是其他地方未定义的响应值? response 未在 .then 函数范围内定义。如果你改为console.log(res) 会怎样?
  • 警报(res);显示 [object Object]
  • console.log(response); 应该会产生一个 ReferenceError,因为您正在尝试访问 const response,因为声明分配尚未完成。我不知道您将如何获得undefined。或者你为什么要尝试记录response,因为它还没有分配
  • 我是新手。你能告诉我如何在页面上打印相同的内容吗?我正在使用表单提交获取请求。现在需要打印表格下方的数据
  • 谢谢 DrewReese,VLAZ。有效。我根据您的建议进行了修改。

标签: node.js reactjs http axios nestjs


【解决方案1】:

您需要在 then 中返回 res 才能访问响应:

const response = await axios
    .get('certificates', {
        params: { sponser },
    })
    .then((res) => {
        console.log(response); //undefined
        alert(res.status);  //200
        alert(res); //[object Object]
        // response is not defined here!
        return res;
    });
console.log(response);

更短的方式:

const response = await axios
    .get('certificates', {
        params: { sponser }
    });
console.log(response);

看来 OP 对 js 来说还是比较新的——我可以推荐这个异步 js 简介:https://javascript.info/async-await

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 2020-10-26
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    相关资源
    最近更新 更多