Categories
JavaScript Answers

How to fix await not waiting for promise with JavaScript async function?

To fix await not waiting for promise with JavaScript async function, we use await on a promise.

For instance, we write

const func = async () => console.log(await getResult());

to call getResult to return a promise.

And then we use await to get the resolve value of the returned promise.

Categories
JavaScript Answers

How to set request header when making connection with JavaScript socket.io-client?

To set request header when making connection with JavaScript socket.io-client, we set the extraHeaders property.

For instance, we write

const socket = io("http://localhost", {
  extraHeaders: {
    Authorization: "Bearer authorization_token_here",
  },
});

to set extraHeaders to an object with the header keys-value pairs.

Categories
JavaScript Answers

How to get Node.js Express to listen only on localhost?

To get Node.js Express to listen only on localhost, we call listen with the port only.

For instance, we write

app.listen(3001);

to only listen to port 3001 on localhost for requests.

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.