Categories
Express JavaScript Answers

How to Serve a Single Static File with Express.js?

Sometimes, we want to serve a single static file with Express.js.

In this article, we’ll look at how to serve a single static file with Express.js.

Serve a Single Static File with Express.js

To serve a single static file with Express.js, we can use the express.static middleware.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

app.use("/foo.txt", express.static(__dirname + '/foo.txt'));

app.get('/', (req, res) => {
  res.send('hello world')
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

to add:

app.use("/foo.txt", express.static(__dirname + '/foo.txt'));

to use the express.static middleware to expose the foo.txt file to the public.

We make it accessible by making a request to “/foo.txt” since that’s the first argument we passed into app.use .

And we make it serve the foo.txt file from the current working directory with:

express.static(__dirname + '/foo.txt')

So when we make a request to /foo.txt , we would see its contents in the response.

Conclusion

To serve a single static file with Express.js, we can use the express.static middleware.

Categories
Express JavaScript Answers

How to Generate robots.txt in Express?

Sometimes, we want to generate a robots.txt file from our Express app.

In this article, we’ll look at how to generate a robots.txt file from our Express app.

Generate robots.txt in Express

To generate a robots.txt file from our Express app, we can create a robots.txt file that returns the text content of the robots.txt file.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('hello world')
});

app.use('/robots.txt', function(req, res, next) {
  res.type('text/plain')
  res.send("User-agent: *\nDisallow: /");
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

to create the /robots.txt route by writing:

app.use('/robots.txt', function(req, res, next) {
  res.type('text/plain')
  res.send("User-agent: *\nDisallow: /");
});

We call res.type to set the MIME type of the response to text/plain .

And we call res.send with the robots.txt content we want to return.

So when we make a GET request to the /robots.txt route, we get:

User-agent: *
Disallow: /

Conclusion

To generate a robots.txt file from our Express app, we can create a robots.txt file that returns the text content of the robots.txt file.

Categories
Express JavaScript Answers

How to Add Response Timeout Feature to an Express.js App?

Sometimes, we want to add a response timeout feature to an Express.js app to end requests that take too long to process.

In this article, we’ll look at how to add a response timeout feature to an Express.js app to end requests that take too long to process.

Add Response Timeout Feature to an Express.js App

To add a response timeout feature to an Express.js app to end requests that take too long to process, we can use the connect-timeout package.

To install it, we run:

npm i `connect-timeout`

Then we can use it by writing:

const express = require('express')
const timeout = require('connect-timeout');
const app = express()
const port = 3000
const haltOnTimedout = (req, res, next) => {
  if (!req.timedout) {
    next();
  }
}

app.use(timeout(120000));
app.use(haltOnTimedout);

app.get('/', (req, res) => {
  res.send('hello world')
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We include the module with require .

Then we create the haltOnTimeout function that checks the req.timedout property to see if the request has timed out.

If it hasn’t timed out, then req.timedout is false and we call next to move forward with the request.

This property is available which we added:

app.use(timeout(120000));

to add the connect-timeout middleware to detect the timeout.

120000 is in milliseconds and it’s the number of milliseconds before the request times out.

Conclusion

To add a response timeout feature to an Express.js app to end requests that take too long to process, we can use the connect-timeout package.

Categories
Express JavaScript Answers

How to Accept form-data Request Data with Express?

Sometimes, we want to accept form-data request data in our Express app.

In this article, we’ll look at how to accept form-data request data in our Express app.

Accept form-data Request Data with Express

To accept form-data request data in our Express app, we can use the body-parser package.

To install it, we run:

npm i body-parser

Then we can use it by writing:

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 3000

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/', (req, res) => {
  res.send(req.body)
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

so that we can accept form-data requests in our Express app.

We call bodyParser.urlencoded to accept form-data requests.

The extended option lets us choose between parsing the URL-encoded data with the querystring library with its set to false or the qs library when it’s set to true .

Therefore, when we make a x-www-form-urlencoded request with some key-value pairs, we should get them in the req.body object.

So we’ll see them returned as the response when we make a POST request to the / route.

Conclusion

To accept form-data request data in our Express app, we can use the body-parser package.

Categories
Express JavaScript Answers

How to Add a Single Routing Handler for Multiple Routes in a Single Line with Express?

Sometimes, we want to add a single routing handler for multiple routes in a single line with Express.

In this article, we’ll look at how to add a single routing handler for multiple routes in a single line with Express.

Add a Single Routing Handler for Multiple Routes in a Single Line with Express

To add a single routing handler for multiple routes in a single line with Express, we can pass in an array of route path patterns that will be handled by one route handler.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

const routes = ['/', '/foo', '/bar', '/baz/:id']
app.get(routes, (req, res) => {
  res.send('hello world')
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We have the routes array that has strings with different route path patterns.

And we use it as the first argument of the app.get method.

Therefore, when we go to / , /foo , /bar or /baz with anything after it, we’ll see hello world displayed.

This also works with app.post , app.delete , app.put , and other route defining methods.

Conclusion

To add a single routing handler for multiple routes in a single line with Express, we can pass in an array of route path patterns that will be handled by one route handler.