Nuxt 3页面展示客户端POST请求响应时刷新报错求助
Nuxt3 客户端POST请求首次加载报错解决方法
错误原因
你遇到的response.value is null报错,是因为首次加载时,useFetch的请求还没完成,response.value还处于null状态,直接访问response.value.title相当于访问null.title,自然触发类型错误。而热重载时请求可能已经完成,所以不会报错。
另外你模板里有个小错误:<p>{{ myResponseText }}</h2>应该改成<p>{{ myResponseText }}</p>,标签要闭合正确。
修正后的代码实现
my-component.vue
<template> <div> <!-- 请求未完成时显示加载提示 --> <div v-if="pending">加载中...</div> <!-- 请求成功且有数据时展示内容 --> <div v-else-if="response"> <h2>{{ response.title }}</h2> <p>{{ response.text }}</p> </div> <!-- 请求失败或无数据时的提示 --> <div v-else>内容加载失败</div> </div> </template> <script setup> // 解构出请求状态pending、响应数据response、错误信息error const { data: response, pending, error } = await useFetch('http://localhost:5000/api/endpoint', { method: 'POST', // 无需手动JSON.stringify,Nuxt会自动处理请求体 body: { tz: Intl.DateTimeFormat().resolvedOptions().timeZone }, // 告诉后端请求体是JSON格式 headers: { 'Content-Type': 'application/json' } }) </script>
index.vue(保持不变即可)
<template> <div> <client-only> <my-component/> </client-only> </div> </template>
关键知识点说明
- 响应式数据的状态判断:
useFetch返回的data是响应式对象,初始值为null,必须通过v-if="response"或者response?.title(可选链操作符)判断数据是否存在,避免访问null的属性。 - 请求状态管理:用
pending可以判断请求是否还在进行中,给用户显示加载提示,提升体验。 - 请求体自动处理:Nuxt3的
useFetch会自动将对象格式的body转为JSON字符串,不用手动调用JSON.stringify。
内容的提问来源于stack exchange,提问作者fidelity
相关产品推荐
相关产品推荐

