DNA
DNA2y ago

Sending proper Content-Type depending on file sent

Hello. Im new to Deno and TypeScript and i wanted to convert one of my older projects (NodeJs and JavaScript). Now, my plan is to send the requested file, which actually does work, but the response doesnt send the proper content-type. What do i have to do in order to get this working properly?
const handler = async (req: Request): Promise<Response> => {
const url = new URL(req.url);

const filePath: string = "./client" + (url.pathname === "/" ? "/index.html" : url.pathname);

try {
const file = await Deno.open(filePath, {read: true});
const readableStream = file.readable;

return new Response(readableStream, {
status: 200,
})
} catch (_error) {
return new Response(`GET ${filePath}`, {status: 404});
}
};
const handler = async (req: Request): Promise<Response> => {
const url = new URL(req.url);

const filePath: string = "./client" + (url.pathname === "/" ? "/index.html" : url.pathname);

try {
const file = await Deno.open(filePath, {read: true});
const readableStream = file.readable;

return new Response(readableStream, {
status: 200,
})
} catch (_error) {
return new Response(`GET ${filePath}`, {status: 404});
}
};
3 Replies
AapoAlas
AapoAlas2y ago
You'd need to place the content-type header yourself. Consider using the file server or serve from std: Those are more "batteries included" servers.
DNA
DNAOP2y ago
Im now using file-server (serveDir), as you told me to, but whenever im requesting a file that doesnt exist in my fsRoot directory, im getting those weird looking messages. How can i prevent this?
const handler = (req: Request) => {
switch (req.url) {
case "/":
return new Response("Hello, World!", {status: Status.OK});

default:
return serveDir(req, {
enableCors: true,
fsRoot: "./client"
})
}
};
const handler = (req: Request) => {
switch (req.url) {
case "/":
return new Response("Hello, World!", {status: Status.OK});

default:
return serveDir(req, {
enableCors: true,
fsRoot: "./client"
})
}
};
DNA
DNAOP2y ago
Found it out already, had to add quiet: true to the serverDir