From bfddd24a2a0c711955a8961fed91abf2a9d935dd Mon Sep 17 00:00:00 2001 From: CanadaHonk Date: Fri, 27 Jan 2023 18:41:13 +0000 Subject: [PATCH] local: add content-type header --- src/lib/local/cdp.js | 19 ++++++++++++++++--- src/lib/local/server.js | 8 +++----- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/src/lib/local/cdp.js b/src/lib/local/cdp.js index bff2acc..ba6939d 100644 --- a/src/lib/local/cdp.js +++ b/src/lib/local/cdp.js @@ -1,6 +1,7 @@ import { basename, dirname, extname, join } from 'path'; import { readFile } from 'fs/promises'; import { log } from '../logger.js'; +import mimeType from '../mimeType.js'; const generatePath = (pathname, indexFile) => { if (pathname === '/') return indexFile; @@ -19,17 +20,29 @@ export default async (CDP, { sessionId, url: givenPath, localUrl }) => { const url = new URL(request.url); const path = join(basePath, generatePath(url.pathname, indexFile)); + const ext = extname(path).slice(1); let error = false; const body = await readFile(path, 'utf8').catch(() => false); if (!body) error = 404; + if (error) return await CDP.sendMessage('Fetch.fulfillRequest', { + requestId, + responseCode: error, + body: Buffer.from('').toString('base64') // CDP uses base64 encoding for request body + }); + return await CDP.sendMessage('Fetch.fulfillRequest', { requestId, - responseCode: error || 200, - body: Buffer.from(error ? '' : body).toString('base64'), // CDP uses base64 encoding for request body - // need to add our own headers or not? + responseCode: 200, + body: Buffer.from(body).toString('base64'), // CDP uses base64 encoding for request body + responseHeaders: [ + { + name: 'Content-Type', + value: mimeType(ext) + } + ] }); } }); diff --git a/src/lib/local/server.js b/src/lib/local/server.js index a6d808e..1d30e40 100644 --- a/src/lib/local/server.js +++ b/src/lib/local/server.js @@ -2,6 +2,7 @@ import { basename, dirname, extname, join } from 'path'; import { readFile } from 'fs/promises'; import { createServer } from 'http'; import { log } from '../logger.js'; +import mimeType from '../mimeType.js'; const generatePath = (pathname, indexFile) => { if (pathname === '/') return indexFile; @@ -18,23 +19,20 @@ export default async ({ url: givenPath, localUrl }) => { const server = createServer(async (req, res) => { const url = new URL(`http://localhost:${port}` + decodeURI(req.url)); const path = join(basePath, generatePath(url.pathname, indexFile)); - - console.log('SERVER', url, path); + const ext = extname(path).slice(1); let error = false; const body = await readFile(path, 'utf8').catch(() => false); if (!body) error = 404; - console.log('SERVER', error); - if (error) { res.writeHead(error); return res.end(); } res.writeHead(200, { - + 'Content-Type': mimeType(ext) }); res.end(body, 'utf8');