D
Deno

help

Sending proper Content-Type depending on file sent

DDNA5/22/2023
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});
}
};
AAapoAlas5/22/2023
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.
DDNA5/22/2023
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"
})
}
};
DDNA5/22/2023
Found it out already, had to add quiet: true to the serverDir

Looking for more? Join the community!