Categories
JavaScript Answers

How to fix Module not found: Error: Can’t resolve ‘crypto’ with JavaScript?

To fix Module not found: Error: Can’t resolve ‘crypto’ with JavaScript, we add the crypto to the browser section of package.json.

For instance, we write

{
  //...
  "browser": {
    "crypto": false
  }
  //...
}

in package.json to disable the crypto module in the browser environment by setting crypto to false.

Categories
JavaScript Answers

How to send image files as API response with Node Express?

To send image files as API response with Node Express, we call res.sendFile.

For instance, we write

app.get("/report/:chart_id/:user_id", (req, res) => {
  //...
  res.sendFile(filePath);
});

to call res.sendFile with the filePath to return the image at the filePath as the response.

Categories
JavaScript Answers

How to accept form data request with Node Express.js?

To accept form data request with Node Express.js, we use the body-parser module.

For instance, we write

const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(bodyParser.urlencoded({ extended: true }));

to call bodyParser.urlencoded to add a middleware to accept form data requests.

Categories
JavaScript Answers

How to add Express.js response timeout with Node.js?

To add Express.js response timeout with Node.js, we use the connect-timeout module.

For instance, we write

const timeout = require("connect-timeout");

const haltOnTimedout = (req, res, next) => {
  if (!req.timedout) {
    next();
  }
};

app.use(timeout(120000));
app.use(haltOnTimedout);

to add the halfOnTimedout function.

In it, we check if the request timed out with req.timedout.

If it’s false, then we call next to call the next middleware.

Then we call app.use to add the timeout middleware to make requests time out after 120000ms.

And we call app.use again to add the haltOnTimedout middleware.

Categories
React Answers

How to detect whether input element is focused within React?

To detect whether input element is focused within React, we check the activeElement property.

For instance, we write

//...
const Component = () => {
  const searchInput = React.useRef(null);
  //...
  if (document.activeElement === searchInput.current) {
    // do something
  }

  return <input type="text" ref={searchInput} />;
};

to create a ref with useRef and assign it to the input.

Then we check if the input is focused with document.activeElement === searchInput.current.

document.activeElement is the element currently focused on and searchInput.current is the input with the ref.