Categories
JavaScript Answers

How to fix Node npm behind a proxy fails with status 403?

To fix Node npm behind a proxy fails with status 403, we set the registry URL.

To do this, we run

npm config set registry http://registry.npmjs.org/

to set the registry URL with npm config set registry.

Categories
JavaScript Answers

How to log response body with Node Express?

To log response body with Node Express, we use express-winston.

For instance, we write

expressWinston.requestWhitelist.push("body");
expressWinston.responseWhitelist.push("body");
app.use(
  expressWinston.logger({
    transports: [
      new winston.transports.Console({
        json: true,
        colorize: true,
      }),
    ],
    meta: true,
    msg: "HTTP {{req.method}} {{req.url}}",
    expressFormat: true,
    colorStatus: true,
    ignoreRoute: (req, res) => {
      return false;
    },
  })
);

to add a logger with expressWinston.logger.

The meta option lets us set whether to log meta data.

msg is the log entry format.

expressFormat lets us set whether to use the default formatting.

colorStatus lets us set whether to color the log entry.

ignoreRoute lets us set the routes to skip logging for.

Categories
JavaScript Answers

How to fix can’t find documents searching by ObjectId using Node Mongoose?

To fix can’t find documents searching by ObjectId using Node Mongoose, we convert the object ID string to an object ID.

For instance, we write

const ObjectId = require("mongoose").Types.ObjectId;
const query = { campaign_id: new ObjectId(campaign._id) };

to set query to an object with the campaign+id to an object ID that we create by calling the ObjectId constructor with the campaign._id string.

Categories
JavaScript Answers

How to use populate and aggregate in same statement with Node Mongoose?

To use populate and aggregate in same statement with Node Mongoose, we call the populate method.

For instance, we write

Patients.populate(result, { path: "patient" }, callback);

to call the populate method with result and an object with the fields to get to populate the result.

callback is a function with the results.

Categories
JavaScript Answers

How to fix Error: Cannot GET / witn Node Express?

To fix Error: Cannot GET / witn Node Express, we add render a template or expose a static folder.

For instance, we write

app.use(express.static(__dirname + "/public"));

app.get("/", (req, res) => {
  res.render("index.ejs");
});

to call app.use with the middleware returned by express.static to expose the /public folder as a static files folder.

We also add a get / route to render the index.ejs template.