Categories
JavaScript Answers

How to redirect a POST request with Node.js Express?

To redirect a POST request with Node.js Express, we call redirect to redirect.

For instance, we write

app.post("/", (req, res) => {
  res.redirect(301, "/test");
});

to call redirect with the status code and the URL of the direct to do the redirect.

Categories
JavaScript Answers

How to get error status code with Node http get?

To get error status code with Node http get, we can listen for the error event.

For instance, we write

const https = require("https");

const request = https.get("https://example.com", (response) => {
  console.log(response.statusCode);
});

request.on("error", (error) => {
  console.error(error.status);
});

to call get to make a request to https://example.com.

We get the statusCode for a normal response with response.statusCode in the callback.

If there’s an error, then the error event callback is called and we get the status from error.status.

We listen for the error event with request.on`.

Categories
JavaScript Answers

How to create a zero filled JavaScript array?

To create a zero filled JavaScript array, we use the fill method.

For instance, we write

const arr = Array(10).fill(0);

to call Array with 10 to create an array with 10 empty slots.

Then we call fill with 0 to fill all the empty slots with 0.

Categories
JavaScript Answers

How to initialize an array’s length in JavaScript?

To initialize an array’s length in JavaScript, we set the array’s length property.

For instance, we write

const test = [];
test.length = 4;

to set the length property of the test array to set its length to 4.

Categories
JavaScript Answers

How to split array into chunks with JavaScript?

To split array into chunks with JavaScript, we use a for loop.

For instance, we write

const chunkSize = 10;
for (let i = 0; i < array.length; i += chunkSize) {
  const chunk = array.slice(i, i + chunkSize);
  //...
}

to use a for loop to loop through i from 0 to the array‘s length minus 1.

We increment i by the chunkSize in each iteration.

In the loop, we call array.slice with i and i + chunkSize to return the slice of the array between index i and i + chunkSize - 1 as a new array.