I have the following front end middleware:
export class FrontendMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
const url = req.originalUrl;
if (url.indexOf('rest') === 1) {
next();
} else if (allowedExt.filter(ext => url.indexOf(ext) > 0).length > 0) {
res.sendFile(resolvePath(url));
} else {
res.sendFile(resolvePath('index.html'));
}
}
}
It works fine with express, but with fastify, res.sendFile
is undefined
, so how can I fix that?
I have the following front end middleware:
export class FrontendMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
const url = req.originalUrl;
if (url.indexOf('rest') === 1) {
next();
} else if (allowedExt.filter(ext => url.indexOf(ext) > 0).length > 0) {
res.sendFile(resolvePath(url));
} else {
res.sendFile(resolvePath('index.html'));
}
}
}
It works fine with express, but with fastify, res.sendFile
is undefined
, so how can I fix that?
4 Answers
Reset to default 21Have a look at this issue. sendFile
has no equivalent method in fastify; you have to do it manually:
const stream = fs.createReadStream(resolvePath('index.html'))
res.type('text/html').send(stream)
You can also store index.html in memory and send it from it:
const bufferIndexHtml = fs.readFileSync('index.html')
res.type('text/html').send(bufferIndexHtml)
An alternative method is to use the fastify-static module provided by Fastify. They have some good examples for sending a file. More information can be found about it here - https://github.com/fastify/fastify-static
Here's an example of sending a file -
const fastify = require('fastify')({logger: true})
const path = require('path')
fastify.register(require('@fastify/static'), {
root: path.join(__dirname, 'public'),
prefix: '/public/', // optional: default '/'
})
fastify.get('/sendHtmlFile', function (req, reply) {
reply.sendFile('myHtml.html') // serving path.join(__dirname, 'public', 'myHtml.html') directly
})
// Run the server!
fastify.listen({ port: 3000 }, (err, address) => {
if (err) throw err
// Server is now listening on ${address}
})
If you use TypeScript, declare it like:
import fastifyStatic from "@fastify/static";
export const server = fastify({
logger: true,
});
server.register(fastifyStatic, {
root: path.join(__dirname, "/.testdata/uploads"),
//prefix: "/public/", // optional: default '/'
//constraints: { host: "example.com" }, // optional: default {}
});
Functions/types like sendFile
will be found.
res.type
? – Kim Kern Commented Apr 28, 2019 at 19:52