expressjsHow do I send a file using Express.js?
To send a file using Express.js, you can use the sendFile
method. This method takes in the path of the file you want to send as its first argument.
For example:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
This will send the index.html
file located in the same directory as the script.
The sendFile
method also takes an optional options object as its second argument. This object can be used to set the root
and dotfiles
properties. The root
property is used to set the root directory from which files are served, and the dotfiles
property is used to specify if dotfiles should be served or not.
For example:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html', {
root: '/home/user/files',
dotfiles: 'deny'
});
});
This will send the index.html
file located in the /home/user/files
directory, and will deny any requests for dotfiles.
Helpful links
More of Expressjs
- How do I find Express.js tutorials on YouTube?
- How can I use Express.js to make an XHR request?
- How can I use Zipkin to trace requests in Express.js?
- How can I use Express.js to prevent XSS attacks?
- How can I parse XML data using Express.js?
- How can I use an ExpressJS webhook to receive data from an external source?
- How can I set up unit testing for an Express.js application?
- How can I set up the folder structure for an Express.js project?
- How can I disable the X-Powered-By header in Express.js?
- How can I use the x-forwarded-for header in Express.js?
See more codes...