Vue组件调用Web服务及event-emitters使用报错修复求助
修复Vue组件调用Web服务与Event-Emitter的三个错误
1. 解决 fetch(...).json is not a function 错误
- 问题根源:
fetch调用后直接链式调用.json()的写法错误,正确流程是先获取响应对象,再调用其.json()方法,同时要先校验响应状态是否正常。 - 修复代码示例:
错误写法(可能):
修复后写法:fetch(url).json().then(data => { /* 处理逻辑 */ })fetch(url) .then(res => { if (!res.ok) throw new Error('请求失败') return res.json() // 必须先拿到响应对象,再调用json()方法 }) .then(data => { /* 处理返回的JSON数据 */ }) .catch(err => console.error(err))
2. 解决 defineEmits are referencing locally declared variables 错误
- 问题根源:Vue的
defineEmits不允许引用本地声明的变量,必须直接传入事件名称的字符串数组或校验对象。 - 修复代码示例:
错误写法(可能):
修复后写法:const myEvent = 'data-loaded' const emit = defineEmits([myEvent])// 直接传入事件名称数组 const emit = defineEmits(['data-loaded']) // 或者用对象定义事件参数校验(可选) const emit = defineEmits({ 'data-loaded': (data) => typeof data === 'object' })
3. 解决 Unexpected token 'D', "Distance: "... is not valid JSON 错误
- 问题根源:后端返回的是纯文本格式(比如
"Distance: 123"),但前端强行用.json()解析,导致JSON格式校验失败。有两种修复方案:- 方案一:前端改为解析文本数据
fetch(url) .then(res => res.text()) // 用text()替代json()解析纯文本 .then(textData => { // 按需处理文本,比如提取距离数值 const distance = textData.split(': ')[1] emit('data-loaded', distance) }) - 方案二:后端修改为返回JSON格式(推荐)
原后端代码(以Node.js为例):
修复后后端代码:// 返回纯文本 res.send('Distance: 123')
此时前端可继续用// 返回标准JSON对象 res.json({ distance: 123 }).json()解析:fetch(url) .then(res => res.json()) .then(data => { emit('data-loaded', data.distance) })
- 方案一:前端改为解析文本数据
内容的提问来源于stack exchange,提问作者Amrmsmb
相关产品推荐
相关产品推荐

