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.

Categories
JavaScript Answers

How to use while loop with promises with JavaScript?

To use while loop with promises with JavaScript, we use async and await.

For instance, we write

const loop = async (value) => {
  let result = null;
  while (result !== "ok") {
    console.log(value);
    result = await doSomething(value);
  }
};

to define the loop function.

In it, we use a while loop that runs until result isn’t 'ok'.

In the loop, we call doSomething which returns a promise and we use await to wait for the promise to finish and return the resolved value.

We set the resolved value to result.

Categories
JavaScript Answers

How to upload a file to Amazon S3 with Node.js?

To upload a file to Amazon S3 with Node.js, we call the putObject method.

For instance, we write

const AWS = require("aws-sdk");
AWS.config.update({
  accessKeyId: "accessKeyId",
  secretAccessKey: "secretAccessKey",
  region: "region",
});

const params = {
  Bucket: "yourBucketName",
  Key: "someUniqueKey",
  Body: "someFile",
};
try {
  const uploadPromise = await new AWS.S3().putObject(params).promise();
  console.log("Successfully uploaded data to bucket");
} catch (e) {
  console.log("Error uploading data: ", e);
}

to call update to connect to AWS.

Then we call putObject with an object with the Bucket, Key and Body to start the upload.

And then we use await to wait for the promise to finish running.

Categories
JavaScript Answers

How to verify if Node.js instance is dev or production?

To verify if Node.js instance is dev or production, we get the NODE_ENV environment variable value.

For instance, we write

const env = process.env.NODE_ENV || "development";

to get the NODE_ENV environment variable value with process.env.NODE_ENV.