fetch()调用Express本地API无法获取期望字符串响应问题排查
解决Express GET接口Fetch调用无法获取字符串响应的问题
问题根源分析
- 请求方法不匹配:后端接口定义的是
GET方法(app.get('/getEntry/:key')),但前端Fetch请求用了POST方法,导致Express无法正确匹配路由处理逻辑。 - Headers配置错误:
Accept字段写错成application.json,正确格式是application/json;且GET请求无需设置Content-Type(无请求体),多余配置可能干扰响应解析。 - 响应处理方式不当:直接获取Blob后未转换为字符串,实际上后端返回的是纯文本内容,用
text()方法可直接拿到目标字符串。
修正后的代码
前端Fetch代码
fetch(`http://${local_IP}:3000/getEntry/${hash}`, { method: 'GET', // 改为与后端匹配的GET方法 headers: { Accept: 'text/html' // 匹配后端返回的text/html类型 }, cache: 'default' }) .then(response => { if (response.ok) { return response.text(); // 直接用text()获取字符串响应 } else { throw new Error('Error: ' + response.status); } }) .then(text => { console.log(text); // 此处将输出目标字符串"Val is val1" console.log(2); }) .catch(error => { console.error('Error:', error); console.log(3); });
可选:后端兼容POST请求(如果需要)
若要让后端同时支持GET和POST,可修改路由:
app.all('/getEntry/:key', (req, res) => { const result = getEntry(req.params.key); res.send(result); return result; });
额外优化说明
从响应头可见后端返回的content-type是text/html; charset=utf-8,用response.text()是最直接的解析方式。若希望后端返回JSON格式,可修改后端代码:
app.get('/getEntry/:key', (req, res) => { const result = getEntry(req.params.key); res.json({ value: result }); // 返回JSON格式数据 return result; });
此时前端可改用response.json()解析,通过value字段获取目标字符串。
内容的提问来源于stack exchange,提问作者totalnoob
相关产品推荐
相关产品推荐

