Categories
JavaScript Answers

How to fix Node.js Hostname/IP doesn’t match certificate’s altnames?

To fix Node.js Hostname/IP doesn’t match certificate’s altnames, we proxy to the target URL.

For instance, we write

const proxy = httpProxy.createProxyServer();

proxy.web(req, res, {
  changeOrigin: true,
  target: "https://example.com:3000",
});

to call proxy.web to proxy requests to https://example.com:3000.

If we use HTTPS, we should include the key and certificate by writing

httpProxy
  .createServer({
    ssl: {
      key: fs.readFileSync("valid-ssl-key.pem", "utf8"),
      cert: fs.readFileSync("valid-ssl-cert.pem", "utf8"),
    },
    target: "https://example.com:3000",
    secure: true,
  })
  .listen(443);

to call add call createServer with the key and cert set.

And we proxy requests to https://example.com:3000.

Categories
JavaScript Answers

How to fix global Node modules not found with JavaScript?

To fix global Node modules not found with JavaScript, we set the NODE_PATH environment variable.

We run

echo $NODE_PATH

to print the value of the NODE_PATH environment variable.

If it’s empty, we add

nano ~/.bash_profile
export NODE_PATH=`npm root -g`
source ~/.bash_profile

to add NODE_PATH to the .bash_profile file to make the global packages visible.

Categories
JavaScript Answers

How to end a session in Express.js and Node.js?

To end a session in Express.js and Node.js, we call the req.session.destroy method.

For instance, we write

req.session.destroy();

to call req.session.destro to end a session with Express.

Categories
JavaScript Answers

How to fix MongoError: connect ECONNREFUSED 127.0.0.1:27017 error in Node.js?

To fix MongoError: connect ECONNREFUSED 127.0.0.1:27017 error in Node.js, we should check that the connection string is correct.

For instance, we write

const uri = "mongodb://0.0.0.0:27017/";
const client = new MongoClient(uri);

to call MongoClient with the uri connection string to make the connection to MongoDB.

Categories
JavaScript Answers

How to fill an input field using Puppeteer and JavaScript?

To fill an input field using Puppeteer and JavaScript, we call the page.evaluate method.

For instance, we write

await page.evaluate(() => {
  const email = document.querySelector("#email");
  email.value = "test@example.com";
});

to call page.evaluate with a callback that gets the input with querySelector.

And we set its value to the input value.