Categories
JavaScript Answers

How to fix TypeScript Error: Property ‘user’ does not exist on type ‘Request’?

To fix TypeScript Error: Property ‘user’ does not exist on type ‘Request’, we add our own interface.

For instance, we weite

import { Request } from "express";
export interface IGetUserAuthInfoRequest extends Request {
  user: string;
}

to add the IGetUserAuthInfoRequest in definitionFile.ts.

IGetUserAuthInfoRequest inerits from the Request interface built into Express.

We add the user property to it.

And then we write

import { Response } from "express";
import { IGetUserAuthInfoRequest } from "./definitionfile";

app.get(
  "/auth/userInfo",
  validateUser,
  (req: IGetUserAuthInfoRequest, res: Response) => {
    res.status(200).json(req.user);
  }
);

to use it when we divide the type of the req parameter in the route handler.

We can then use req.user without errors.

Categories
JavaScript Answers

How to create global variables accessible in all views using Express and Node.js?

To create global variables accessible in all views using Express and Node.js, we set the app.locals property.

For instance, we write

app.locals.baseUrl = "http://www.example.com";

to set the app.locals.baseUrl property to the value we want.

Then we can get the value in our middlewares with

const baseUrl = req.app.locals.baseUrl;
Categories
JavaScript Answers

How to redirect a user to an external URL with Node Express?

To redirect a user to an external URL with Node Express, we call res.status and redirect.

For instance, we write

app.get("/where", (req, res) => {
  res.status(301).redirect("https://www.example.com");
});

to call res.status with 301 to return the 301 moved permanently status.

And then we call redirect to redirect to https://www.example.com.

Categories
JavaScript Answers

How to convert Node.js MongoDB object id to string?

To convert Node.js MongoDB object id to string, we call the toString method.

For instance, we write

console.log(user._id.toString());

to call toString to convert the _id object ID to a string.

Categories
JavaScript Answers

How to fix error when running brew install node on Mac?

To fix error when running brew install node on Mac, we set a few folders’ owners to the current user.

To do this, we run

sudo chown -R `whoami`:admin /usr/local/include/node
sudo chown -R `whoami`:admin /usr/local/bin
sudo chown -R `whoami`:admin /usr/local/share
sudo chown -R `whoami`:admin /usr/local/lib/dtrace 

to set the owner of the /usr/local/include/node, /usr/local/bin, /usr/local/share, and /usr/local/lib/dtrace folders to the current user.

Then we overwrite node with

brew link --overwrite node