Categories
JavaScript Answers

How to fix CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response with Node?

To fix CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response with Node, we use the cors package.

To use it, we write

const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
app.options("*", cors());

to call app.use with the middleware returned by cors to enable CORS in our Express app.

Categories
JavaScript Answers

How to fix this error TypeError [ERR_INVALID_CALLBACK]: Callback must be a function with Node?

To fix this error TypeError [ERR_INVALID_CALLBACK]: Callback must be a function with Node, we pass in a function as the callback.

For instance, we write

const fs = require("fs");

fs.readFile("readMe.txt", "utf8", (err, data) => {
  fs.writeFile("writeMe.txt", data, (err, result) => {
    if (err) console.log("error", err);
  });
});

to call readFile with the callback as the 3rd argument.

And we call writeFile with the callback as the 3rd argument.

Categories
JavaScript Answers

How to fix document is not defined with Next.js and JavaScript?

To fix document is not defined with Next.js and JavaScript, we can disable server side rendering for specific components.

For instance, we write

import dynamic from "next/dynamic";

const DynamicComponentWithNoSSR = dynamic(
  () => import("../components/helloo"),
  { ssr: false }
);

function Home() {
  return (
    <div>
      <Header />
      <DynamicComponentWithNoSSR />
      <p>HOME PAGE is here!</p>
    </div>
  );
}

export default Home;

to import the hello component with import and disable server side rendering on it with { ssr: false }.

Then we can use it only in the browser environment.

Categories
JavaScript Answers

How to write base64 image-file with Node?

To write base64 image-file with Node, we call writeFile.

For instance, we write

const image = "data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAA..kJggg==";
const data = image.replace(/^data:image\/\w+;base64,/, "");

fs.writeFile(fileName, data, { encoding: "base64" }, (err) => {
  //...
});

to call writeFile with the MIME type part of the base64 string removed.

And we set encoding to 'base64' to convert the base64 string to binary content.

We get errors from err in the callback.

Categories
JavaScript Answers

How to check if a JSON is empty in Node?

To check if a JSON is empty in Node, we check if the object has any keys.

For instance, we write

const isEmptyObject = (obj) => {
  return !Object.keys(obj).length;
};

//...

if (isEmptyObject(query)) {
  // ...
} else {
  // ...
}

to define the isEmptyObject function.

In it, we call Object.keys to get the keys of obj in an array.

Then we check if its length is 0 to see if obj is empty.

Then we use an if statement to check if query is empty.