Categories
Node.js Tips

Node.js Tips — Test File Uploads, App-Wide headers, Caching

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

Programmatically Stop and Restart Express Servers to Change Ports

We can stop the server and restart it by writing:

server.on('close', () => {
  server.listen(3000);
});

server.listen(8000, () => {
  server.close();
});

We added a listener for the close event that’s run when the server is closed.

Then we call listen with a port.

We have the callback that calls the close method that triggers the close event.

And then the callback we passed to server.on will run.

Automatically Add Header to Every “render” Response

We can add a header to every render response by creating our own middleware to add the response header.

For instance, we can write:

app.get('/*', (req, res, next) => {
  res.header('X-XSS-Protection' , 0);
  next();
});

We add the X-XSS-Protection custom response header with value 0.

We can make the middleware run app-wide by writing:

app.use((req, res, next) => {
  res.set('X-XSS-Protection', 0);
  next();
});

Then we can add a test by installing Mocha and the hipper package by running:

npm install --save-dev mocha hippie

Also, we can test that by writing:

describe('Response Headers', () => {
  it('responds with header X-XSS-Protection with value 0', (done) => {
    hippie(app)
      .get('/foo')
      .expectHeader('X-XSS-Protection', 0)
      .end(done);
  });
});

We import the app object which we have in the previous example.

Then we pass that to hippie and call a route and then call expectHeader to check that the header returned.

And then we call end with done to finish the test.

Set Cache Control Header for Dynamic Data Express

We can set the Cache-Control header with our own value.

For instance, we can write:

res.set('Cache-Control', 'public, max-age=86400');

which sets the Cache-Control header to one day, which is 86400 seconds.

We can use it in a middleware by writing:

app.use((req, res, next) => {
  res.set('Cache-Control', 'public, max-age=86400');
  next();
})

We just put the line in and call next to call the next middleware.

Express Serve Static Folder Relative to Parent Directory

We can serve a folder as a static folder relative to a directory with path.join .

For instance, we can write:

const path = require('path');
const express = require('express');
const app = express();

app.use(express.static(path.join(__dirname, '../public')));

We call express.static to set the public folder which is one level above the current folder as a folder for serving static files.

Send Multiple Response Chunks in one Route

If need to send our responses in chunks, we can use the response.write method.

For instance, we can write:

response.write("foo");
response.write("bar");
response.end();

We called response.write twice to send different parts of the response,

Then we call response.end to finish sending the response.

Unit Test with a File Upload in Mocha

We can test file upload by writing:

const should = require('should');
const supertest = require('supertest');
const request = supertest('localhost:3000');

describe('upload', () => {
  it('a file', (done) => {
    request
      .post('/upload')
      .field('foo', 'bar')
      .attach('image', 'pic.jpg')
      .end((err, res) => {
        res.should.have.status(200);
        done();
      });
  });
});

We make a POST request with supertest and call attach to attach the file with the given name.

field has the text fields that we want to submit with the file upload.

Then we check that the response is 200 with the callback.

We can attach more than one field or file attachment.

Listen to socket.io Errors in an Express App

We can listen to socket.io in an Express app by passing in the server object returned by listen into the socket.io function.

For instance, we can write:

const express = require('express');
const app = express();
const server = app.listen(port);
const io = require('socket.io')(server);

We pass the server into the function returned by the socket.io package,.

Also, we can write:

const http = require('http');
const express = require('express');
const app = express();

const server = http.createServer(app);
consr io = require('socket.io').listen(server);
server.listen(80);

We pass the server returned from the http module into the listen method instead.

Conclusion

We can set the header by using the res.header method.

There are multiple ways to listen to errors from socket.io in an Express app.

We can also test file uploads with Supertest.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *