Categories
JavaScript Answers

How to install and run TypeScript locally in npm?

To install and run TypeScript locally in npm, we add a script to run the tsc command.

For instance, in package.json, we write

{
  "name": "foo",
  "scripts": {
    "tsc": "tsc"
  },
  "dependencies": {
    "typescript": "^1.8.10"
  }
}

to add the tsc script which runs the tsc command.

Then we run

npm run tsc 

to install the tsc command.

Categories
JavaScript Answers

How to add logging for an Express.js Node app?

To add logging for an Express.js Node app, we use the morgan package.

For instance, we write

const addRequestId = require("express-request-id")({ setHeader: false });
app.use(addRequestId);

const morgan = require("morgan");
morgan.token("id", (req) => req.id.split("-")[0]);

app.use(
  morgan("[:date[iso] #:id] Started :method :url for :remote-addr", {
    immediate: true,
  })
);

app.use(
  morgan(
    "[:date[iso] #:id] Completed :status :res[content-length] in :response-time ms"
  )
);

app.use("/api", router);

to use the express-request-id to add an ID to each request and make it available with the req.id property.

And thenm we call app.use with the middleware returned by morgan.

We call morgan with the format string for each log entry to add logging.

Categories
JavaScript Answers

How to fix the UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block error with Node?

To fix the UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block error with Node, we add a catch block.

For instance, we write

router.get("/emailfetch", authCheck, async (req, res, next) => {
  try {
    const emailFetch = await gmaiLHelper.getEmails(
      req.user._doc.profile_id,
      "/messages",
      req.user.accessToken
    );
    res.send(emailFetch.data);
  } catch (err) {
    next(err);
  }
});

to wrap our code that might thrown an error with a try block.

Then when an error is thrown, the code in the catch block will run.

Categories
JavaScript Answers

How to set the content-type of request header when using Fetch API with JavaScript?

To set the content-type of request header when using Fetch API with JavaScript, we set the headers property.

For instance, we write

const options = {
  method: method,
  headers: new Headers({ "content-type": "application/json" }),
  mode: "no-cors",
};

options.body = JSON.stringify(body);
const res = await fetch(url, options);

to set the headers property to a Headers object with the content-type request header.

Categories
JavaScript Answers

How to get data passed from a form in Express and Node.js?

To get data passed from a form in Express and Node.js, we use the body-parser module.

For instance, we write

const bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({ extended: true }));

app.post("/game", (req, res) => {
  res.render("template", { name: req.body.name });
});

to call app.use to use the middleware returned by bodyParser.urlencoded to make our app parse form data request data.

Then we get the request body data from req.body as an object in the post /game route handler.