如何在浏览器中打开预览pdf,而不是下载

const http = require('http'); const nodefetch = require('node-fetch'); const PORT = 3000; const server = http.createServer(async (req, res) => { if (req.url === '/get-pdf' && req.method === 'GET') { let PDF_URL = req.query.url let pass = await checkUrl(PDF_URL) if (!pass) { res.send('Not Found'); return } // 请求第三方PDF文件 let data = null try { data = await nodefetch(PDF_URL, { method: "GET", headers: { "Content-Type": "application/pdf", } }) } catch (error) { data = { body: 'error' } } // 重点在这里 res.setHeader('Content-Type', 'application/pdf') res.setHeader('Content-Disposition', 'inline') data.body.pipe(res) } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Not Found'); } }); function checkUrl(url){ // 可以配置白名单,或者域名校验一下 url = decodeURIComponent(url) let domain = url.split('/')[2] if (domain === 'localhost:3000'){ return true } else { return false } server.listen(PORT, () => { console.log(`Server is listening on port ${PORT}`); });
上一篇:WebScoket 使用教程


下一篇:机器学习中的朴素贝叶斯