Categories
JavaScript Answers

How to install a list of many global packages with Yarn and JavaScript?

To install a list of many global packages with Yarn and JavaScript, we run the yarn global add command.

To do this, we run

yarn global add nodejs

to install global packages for Node.js.

Categories
JavaScript Answers

How to make Node.js http ‘get’ request with query string parameters?

To make Node.js http ‘get’ request with query string parameters, we set the qs property.

For instance, we write

const request = require("request");
const propertiesObject = { field1: "test1", field2: "test2" };

request({ url, qs: propertiesObject }, (err, response, body) => {
  if (err) {
    console.log(err);
    return;
  }
  console.log(response.statusCode);
});

to call request to make a request to url and we set the quert string by setting qs to an object with the keys and values for the query string.

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

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.