搭配Node服务的React应用如何加载显示网络驱动器内的动态PDF
问题修复方案
你的代码存在服务端、客户端共4处核心问题,分别对应修复如下:
一、服务端问题与修正
原有问题
res.sendFile()方法接收的参数是文件绝对路径字符串,你传入了fs.createReadStream返回的流对象,参数类型完全不匹配- Windows系统下的文件路径反斜杠需要转义,
"R:\Test.pdf"中的\T会被识别为制表符,实际读取路径错误 - 缺失错误处理逻辑,文件读取失败、路径不存在等异常没有捕获,会直接返回异常响应
修正后代码
写法1:直接使用sendFile(推荐,最简单)
const path = require('path'); function getTestDoc(req, res, next) { // 用path.join拼接避免转义问题 const pdfPath = path.join('R:', 'Test.pdf'); res.contentType("application/pdf"); // 传入路径字符串,增加错误回调 res.sendFile(pdfPath, (err) => { if (err) { console.log('文件发送失败:', err); res.status(err.status || 500).end(); } }); }
写法2:使用流管道传输
const fs = require('fs'); const path = require('path'); function getTestDoc(req, res, next) { const pdfPath = path.join('R:', 'Test.pdf'); const stream = fs.createReadStream(pdfPath); // 监听流错误 stream.on('error', (err) => { console.log('文件读取失败:', err); res.status(404).end(); }); res.contentType("application/pdf"); // 用pipe把文件流传输到响应对象 stream.pipe(res); }
二、客户端问题与修正
原有问题
fetch返回的response.body是可读流对象,不能直接放入Blob构造参数,需要调用异步方法response.blob()获取完整的Blob对象- 存在语法错误:
window.open(fileUrl))多了一个多余的右括号,then回调也没有正确闭合 - 缺失响应状态校验,接口返回4xx/5xx错误时也会直接生成Blob,导致PDF解析失败
修正后代码
function getTestDoc() { const requestOptions = { method: 'GET', responseType: "blob", headers: authHeader(), }; return fetch(`${apiUrl}/mo/gettestdoc`, requestOptions) .then(async (response) => { // 先校验响应状态 if (!response.ok) throw new Error('接口请求失败'); // 调用blob方法获取文件对象 const file = await response.blob(); const fileUrl = URL.createObjectURL(file); window.open(fileUrl); }) .catch(err => { console.log('PDF加载失败:', err); }); }
额外排查点
如果修改后仍然报错,可以按以下顺序排查:
- 确认Node服务进程有权限读取R盘的Test.pdf文件,网络映射盘符需要确认运行服务的账号有访问权限
- 确认返回的响应头
Content-Type确实为application/pdf,可以在浏览器开发者工具的网络面板查看接口返回的响应头和响应大小是否和源文件一致
内容的提问来源于stack exchange,提问作者ferdinand-zf
相关产品推荐
相关产品推荐

