"events.js: 377" occurs when I am running the app.js as a node server on Hyper cmd

Viewed 1167

"events.js: 377" occurs when I am running the app.js as a node server on Hyper. Please also mention the full descriptive meaning of this "events.js: 377" and how we can figure it out this.

I am coding a Signup Newsletter and the code related to .html, .js and .css files are attached below.

I have many times changed the pattern of my code but I am not able to run the app.js as it is getting crashed every time.

If anybody knows about the solution then please answer.

Given below is link of the image of the error that is shown on the hyper when I run app.js as a server and it gets crashed.

Error Stack

The below given code is of app.js :

    const express = require("express");
    const https = require("https");
    const bodyParser = require("body-parser");
    const request = require("request");
    const app = express();
    app.use(express.static("public"));
    app.use(bodyParser.urlencoded({extended: true}));
    app.get("/", function(req, res){
      res.sendFile(__dirname + "/signup.html");
    })
    app.post("/", function(req, res){
      const firstName = req.body.fName;
      const lastName = req.body.lName;
      const email = req.body.email;
      const data = {
        members:[
          {
            email_address: email,
            status: "subscribed",
            merge_fields: {
              FNAME: firstName,
              LNAME: lastName
            }
          }
        ]
      }
    });
      const jsonData = JSON.stringify("data");
      const url = "https://us5.api.mailchimp.com/3.0/lists/21760b9a041";
    const options = {
      method: "POST",
      auth: "xxxx"
    }
    const requestt = https.request(url, options, function(response) {
        response.on("data", function(data){
          console.log(JSON.parse(data));
        })
    requestt.write(jsonData);
    requestt.end
    });
    app.listen("3000", function(){
      console.log("Server is running on port 3000");
    });

The given below code is of signup.html :

***<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Hugo 0.88.1">
    <title>Signin Template · Bootstrap v5.1</title>
    <link rel="canonical" href="https://getbootstrap.com/docs/5.1/examples/sign-in/">
<!-- When Internet will be ON only then this link of Bootstrap will be applied to your website. -->
    <!-- Bootstrap core CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-uWxY/CJNBR+1zjPWmfnSnVxwRheevXITnMqoEIeG1LJrdI0GlVs/9cVSyPYXdcSF" crossorigin="anonymous">
    <!-- Favicons -->
<link rel="apple-touch-icon" href="/docs/5.1/assets/img/favicons/apple-touch-icon.png" sizes="180x180">
<link rel="icon" href="/docs/5.1/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="icon" href="/docs/5.1/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
<link rel="manifest" href="/docs/5.1/assets/img/favicons/manifest.json">
<link rel="mask-icon" href="/docs/5.1/assets/img/favicons/safari-pinned-tab.svg" color="#7952b3">
<link rel="icon" href="/docs/5.1/assets/img/favicons/favicon.ico">
<meta name="theme-color" content="#7952b3">
    <!-- Custom styles for this template -->
    <link href="css/styles.css" rel="stylesheet">
  </head>
  <body class="text-center">
  <form class="form-signin" action="/" method="POST">
    <img class="mb-4" src="Image/lab.jpg" alt="" width="72" height="57">
    <h1 class="h3 mb-3 fw-normal">Signup to my Newsletter.</h1>
      <input type="text" name = fName class="form-control middle" id="inputPassword" placeholder="First Name" required>
      <input type="text" name = lName class="form-control top" id="inputEmail" placeholder="Last Name" required autofocus>
      <input type="email"name = email  class="form-control bottom" placeholder="Email" required>
    <button class="w-100 btn btn-lg btn-primary btn-block" type="submit">Sign Me Up!</button>
    <p class="mt-5 mb-3 text-muted">&copy; 2017–2021</p>
  </form>
  
  </body>
</html>***

The given below code is of styles.css :


body {
  height: 100%;
}
body {
  display: flex;
  align-items: center;
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: #f5f5f5;
}
.form-signin {
  width: 100%;
  max-width: 330px;
  padding: 15px;
  margin: auto;
}
.form-signin .checkbox {
  font-weight: 400;
}
.form-signin .form-floating:focus-within {
  z-index: 2;
}
.top {
  margin-bottom: 2px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}
.middle {
  border-radius: 0;
  margin-bottom: 2px;
}
.bottom{
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}

2 Answers

Looks like you are very new to javascript. I would recommend formatting your code a bit better and you might catch errors like these a bit easier.

The exact cause of your error is that you are getting an error when making your API request to mailchimp and you do not have an error handler. Secondarily the reason you are likely getting that error is due to the fact that you are just sending them the literal string 'data' and nothing else.

Your code when properly formatted looks like this:

app.post("/", function(req, res) {
  const firstName = req.body.fName;
  const lastName = req.body.lName;
  const email = req.body.email;
  const data = {
    members: [{
      email_address: email,
      status: "subscribed",
      merge_fields: {
        FNAME: firstName,
        LNAME: lastName
      }
    }]
  }
});

const jsonData = JSON.stringify("data");
const url = "https://us5.api.mailchimp.com/3.0/lists/21760b9a041";
const options = {
  method: "POST",
  auth: "xxxx"
};

const requestt = https.request(url, options, function(response) {
  response.on("data", function(data) {
    console.log(JSON.parse(data));
  });
  requestt.write(jsonData);
  requestt.end
});

Note that your post to mailchimp is outside of your app.post callback handler. Due to that code's location it will execute the moment you run your code. First you need to move this code inside your route handler.

app.post("/", function(req, res) {
  const firstName = req.body.fName;
  const lastName = req.body.lName;
  const email = req.body.email;
  const data = {
    members: [{
      email_address: email,
      status: "subscribed",
      merge_fields: {
        FNAME: firstName,
        LNAME: lastName
      }
    }]
  };

  const jsonData = JSON.stringify("data");
  const url = "https://us5.api.mailchimp.com/3.0/lists/21760b9a041";
  const options = {
    method: "POST",
    auth: "xxxx"
  };

  const requestt = https.request(url, options, function(response) {
    response.on("data", function(data) {
      console.log(JSON.parse(data));
    });
    requestt.write(jsonData);
    requestt.end
  });

});

This will prevent your code from executing the moment you run your code.

Secondly you need to add an error handler to your request method so that if an error occurs you do not cause an unhandled error to crash your program. That is what is causing you to see the Unhandled 'error' event message right below events:377.

const requestt = https.request(url, options, function(response) {
  response.on("data", function(data) {
    console.log(JSON.parse(data));
  });
  response.on("error", function(error) {
    console.error('Error from mailchimp', error);
  });
  requestt.write(jsonData);
  requestt.end
});

Lastly, the actual error you are seeing is socket hang up. This error is generally a network error meaning that your client's TCP requests to the target server were dropped/rejected or otherwise terminated before they could be completed. This may be a result of not actually calling the end function when making your request. Specifically you have requestt.end, which is a function, but you are not calling it, should be requestt.end();. If this doesn't resolve it then you may want to check the network connectivity of the computer you are running this code on.

Another error I noticed in your code:

const jsonData = JSON.stringify("data");

You probably mean to send the data object that you are creating, in that case you do not want to wrap data in quotes as it is a variable name, not a string. Instead it should be:

const jsonData = JSON.stringify(data);

I also experienced the same issue and I got this fixed. The root cause at my end was that port number I used was engaged/used at another program.

app.listen("3000", function(){...

Once I closed the other program that was using this port number, my program worked fine.

Related