Axios 返回未定义

Axios is returning undefined

当我向 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]
        });
};

你能帮我解决这个问题吗?

您需要 return res in then 才能访问响应:

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