Categories
Node.js Tips

Node.js Tips — Body Parser Errors, Static Files, and Update Collections

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.

Register Mongoose Models

We can register Mongoose Models by exporting them and then requiring them in our Express app’s entry point.

For instance, we can write the following in models/User.js:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
  name: String
});

mongoose.model('User', userSchema);

Then in our app.js file, we can write:

mongoose.connect("mongodb://localhost/news");
require("./models/User");

const users = require('./routes/users');

const app = express();

Requiring the ./models/User.js will make it run the code to register the model.

Catch Express body-parser Error

We can catch Express body-parser errors with our own middleware.

For instance, we can write:

app.use( (error, req, res, next) => {
  if (error instanceof SyntaxError) {
    sendError(res, 'syntax error');
  } else {
    next();
  }
});

We can check if error is an instance of SyntaxError and do something with it.

Otherwise, we call next to continue to the next middleware.

Route All Requests to index.html in an Express App

We can route all requests to index.html in an Express app by using rthe sendFile method in one route handler.

For instance, we can write:

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

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

server.get('/foo', (req, res) => {
  res.send('ok')
})

server.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname, '/index.html'));
})

const port = 8000;
server.listen(port)

We redirect all requests to index.html with a catch-all route at the end.

This way, we can still have some routes that do something else.

The foo route responds with ok .

express.static serves static content.

Basic Web Server with Node.js and Express for Serving HTML File and Assets

We can use the express.static middleware to serve static assets.

For instance, we can write:

const express = require('express');
const app = express();
const http = require('http');
const path= require('path');
const httpServer = http.Server(app);

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

app.get('/', (req, res) => {
  res.sendfile(path.join(__dirname, '/index.html'));
});
app.listen(3000);

We create a server with the express.static middleware to serve static files from the assets folder.

Then we create a GET route to render index.html .

We can also use connect to do the same thing:

const util = require('util');
const connect = require('connect');
const port = 1234;

connect.createServer(connect.static(__dirname)).listen(port);

We call createServer to create a web server.

Then we use connect.static to serve the current app folder as a static folder.

Gzip Static Content with Express

We can use the compression middleware to serve static content with Gzip.

For instance, we can write:

const express = require('express');
const compress = require('compression');
const app = express();
app.use(compress());

Find the Size of a File in Node.js

We can use the statSync method to get the size pf a file.

For instance, we can write:

const fs = require("fs");
const stats = fs.statSync("foo.txt");
const fileSizeInBytes = stats.size

We call statSync to return an object with some data about the file.

The size in bytes is in the size property.

Automatically Add Header to Every “render” Response

We can use the res.header method to return a header for every response.

For instance, we can write:

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

to create a middleware to set the X-XSS-Protection header to 0.

Update Child Collection with Mongoose

We get the updated collection after the update in the callback.

For instance, we can write:

Lists.findById(listId, (err, list) => {
  if (err) {
    ...
  } else {
    list.items.push(task)
    list.save((err, list) => {
      ...
    });
  }
});

We called findById to get the collection.

Then we call push on the items child collection.

Finally, we call list.save to save the data and get the latest list in the list array of the save callback.

Also, we can use the $push operator to do the push outside the callback:

Lists.findByIdAndUpdate(listId, {$push: { items: task }}, (err, list) => {
  //...
});

We call findByIdAndUpdate with the listId to get the list.

Then we set items with our task object and use $push to push that.

Then we get the latest data from the list parameter in the callback.

Conclusion

We can register Mongoose models by running the code to register the schema.

There’s more than one way to add an item to a child collection.

We can serve static files with Express or Connect.

We can catch body-parser errors.

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 *