Categories
JavaScript Answers

How to upload file using POST request in Node.js?

To upload file using POST request in Node.js, we call the request function.

For instance, w write

request(
  {
    url: "http://example.com",
    method: "POST",
    formData: {
      regularField: "someValue",
      regularFile: someFileStream,
      customBufferFile: {
        value: fileBufferData,
        options: {
          filename: "myfile.bin",
        },
      },
    },
  },
  handleResponse
);

to call request to make a post request to http://example.com

We set formData to an object with the key-value pairs for the form data object.

The file is set as the value of regularFile.

We set it to a stream.

handleResponse is a function that’s called when a response is received.

Categories
JavaScript Answers

How to install LTS version of Node.js via homebrew?

To install LTS version of Node.js via homebrew, we run the brew install command.

To install it, we run

brew install node@8

to install Node 8.

Then we link it with

brew link --force node@8

to make it visible.

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.