You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt中useFetch调用返回类型异常,如何获取响应值?

问题:Nuxt中useFetch返回响应类型异常,如何获取实际返回值?

调用接口可以正常执行,但响应的返回类型异常,不知道怎么获取调用返回的实际值。

我的前端代码(pages/auth/login.vue):

async login() {
    try {
        const { data } = await useFetch('/api/auth/login', {
            method: 'post',
            body: {
               username: this.username,
               password: this.password
            }
        });
        console.log(data)
    } catch (error) {
        console.error('Error during login:', error);
        this.loginError = true;
    }
}

后端代码(server/api/auth/login.tsx):

export default defineEventHandler(async (event) => {
    const { username, password } = await readBody(event)

    return {
        status: "200",
        message: "Lgon usccessful",
        user: username
     }
})

解答

这是Nuxt useFetch的正常特性——它返回的data是响应式的ref对象,不是直接的原始响应数据。要拿到实际返回值,你需要访问data.value:

  1. 修改前端代码中的console.log(data)为console.log(data.value),就能看到接口返回的真实对象了。
  2. 如果需要使用返回的数据,比如提取message或user字段,直接从data.value中读取即可。

修改后的前端代码示例:

async login() {
    try {
        const { data } = await useFetch('/api/auth/login', {
            method: 'post',
            body: {
               username: this.username,
               password: this.password
            }
        });
        // 访问ref的value属性获取实际响应数据
        console.log(data.value);
        // 示例:提取并使用返回字段
        if (data.value) {
            console.log('登录提示:', data.value.message);
            console.log('当前用户:', data.value.user);
        }
    } catch (error) {
        console.error('Error during login:', error);
        this.loginError = true;
    }
}

另外注意后端代码里的拼写错误:Lgon usccessful应该修正为Login successful,虽然不影响功能,但建议修正避免混淆。


内容的提问来源于stack exchange,提问作者backfisch_2_go

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 17:55:01