Categories
JavaScript Answers

How to use .env variables in main app module file for database connection with Node Nest.js?

To use .env variables in main app module file for database connection with Node Nest.js, we can use the dotenv package.

To install it, we run

npm install dotenv

Then we add the scripts with

{
  "scripts": {
    //...
    "start:local": "NODE_ENV=local npm run start",
    "start:dev": "NODE_ENV=dev npm run start"
  }
}

to set the NODE_ENV environment variable before starting the app.

Then we load the .env file for the environment with

require("dotenv").config({ path: `../${process.env.NODE_ENV}.env` });

We get the NODE_ENV environment variable with process.env.NODE_ENV.

And we call config to load the .env file at the path.

Categories
JavaScript Answers

How to use Node Nest.js Logging service?

To use Node Nest.js Logging service, we use the Logger constructor.

For instance, we write

@Controller()
export class AppController {
  private readonly logger = new Logger(AppController.name);

  @Get()
  async get() {
    this.logger.log("Getting stuff");
  }
}

to create a Logger object with the name of the controller.

Then we call logger.log to log some text.

Categories
JavaScript Answers

How to fix Node.js connect only working on localhost?

To fix Node.js connect only working on localhost, we call listen with '0.0.0.0'.

For instance,. we write

const app = connect().use(connect.static("public")).listen(3000, "0.0.0.0");

to call listen with "0.0.0.0" to listen for requests from all IP addresses.

Categories
JavaScript Answers

How to make HTTP requests with gzip/deflate compression with Node?

To make HTTP requests with gzip/deflate compression with Node, we set the gzip property.

For instance, we write

request(
  { method: "GET", uri: "http://www.example.com", gzip: true },
  (error, response, body) => {
    console.log(response.headers["content-encoding"]);
    console.log(body);
  }
);

to call request with an object with the gzip option set to true to make request with gzip compression.

Then we get the response headers from response.headers and the response body from body.

Categories
JavaScript Answers

How to fix Node and MySQL – ER_ACCESS_DENIED_ERROR Access denied for user ‘root’@’localhost’ error?

To fix Node and MySQL – ER_ACCESS_DENIED_ERROR Access denied for user ‘root’@’localhost’ error, we should make sure we connect with the right credentials.

For instance, we write

const mysql = require("mysql");
const connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
});

to call createConnection with an object with the user userame and password password to the host host.