Categories
JavaScript Answers

How to add route with optional parameter after root in Node.js Express?

To add route with optional parameter after root in Node.js Express, we add a question mark after the route parameter placeholder.

For instance, we write

app.get("/api/v1/tours/:cId/:pId/:batchNo?", (req, res) => {
  console.log(req.params.cId);
  console.log(req.params.pId);
  console.log(req.params.batchNo);
});

to add the option batchNo route parameter.

We get its value from req.params.batchNo.

Categories
JavaScript Answers

How to add Gzip compression with Node.js?

To add Gzip compression with Node.js, we use the compression package.

To install it, we run

npm install compression

Then we use it by writing

const express = require("express");
const compression = require("compression");

const app = express();
app.use(compression());

to call app.use with the middleware returned by the compression function to add gzip compression to our Express app.

Categories
JavaScript Answers

How to fix Mongoose Schema hasn’t been registered for model error with JavaScript?

To fix Mongoose Schema hasn’t been registered for model error with JavaScript, we require all the model files.

For instance, we write

const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/news");
require("./models/Posts");
require("./models/Comments");

to call require to require the Post and Comments schema files to register them.

Categories
JavaScript Answers

How to prevent SQL injection in Node.js?

To prevent SQL injection in Node.js, we use the node-mysql-native library.

For instance, we write

const userId = 5;
const query = connection.query(
  "SELECT * FROM users WHERE id = ?",
  [userId],
  (err, results) => {
    //....
  }
);

to make a select query with the query method.

? is a placeholder for userId.

Therefore, results would be the query result for the

SELECT * FROM users WHERE id = 5

command.

Categories
JavaScript Answers

How to prevent Node.js from exiting while waiting for a callback?

To prevent Node.js from exiting while waiting for a callback, we use the EventEmitter to wait for the event.

For instance, we write

const eventEmitter = new process.EventEmitter();

client.connect((err) => {
  eventEmitter.emit("myEvent", { something: "Bla" });
});

eventEmitter.on("myEvent", (myResult) => {
  process.stdout.write(JSON.stringify(myResult));
});

to create an EventEmitter objbect.

We emit the myEvent event with emit with { something: "Bla" } as the payload.

Then we listen for the myEvent event with on and get the payload from myResult.