Clicking on the Node.js subscription button sends me to the local host 127.0.0.1

I'm encountering an issue where clicking the subscribe button redirects my page to 127.0.0.1 and nothing appears in the console.log. Can anyone help me understand why this is happening?

HTML

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Abonelik</title>
      <link rel="stylesheet" 
         href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
         integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" 
         crossorigin="anonymous">
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
         integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" 
         crossorigin="anonymous"></script>
      <link rel="stylesheet" href="signin.css">
   </head>
   <body>
      <div class="parent-wrapper">
         <span class="close-btn glyphicon glyphicon-remove"></span>
         <div class="subscribe-wrapper">
            <h4>Abone Olun</h4>
            <form action="/" method="POST">
               <input type="text" name="fname" class="subscribe-input" placeholder="Adınız">
               <input type="text" name="lname" class="subscribe-input" placeholder="Soyadınız">
               <input type="email" name="email" class="subscribe-input" placeholder="Mail Adresiniz">
               <button type="submit">Abone Ol</button>
            </form>
         </div>
      </div>
   </body>
</html>  

Nodejs

//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({
    extended: true
}));
app.get("subs", function(req, res) {
    res.sendFile(__dirname + "/signup.html");
});
app.post("/", function(req, res) {
    const mail = req.body.email;
    const ilkad = req.body.fname;
    const soyad = req.body.lname;
    console.log(fname, lname, email);
    const data = {
        members: [{
            email_address: mail,
            status: "Subscribed",
            merge_fields: {
                FNAME: fname,
                LNAME: lname,
            }
        }]
    };
    const jData = JSON.stringify(data);
    const url = "https://usX.api.mailchimp.com/3.0/lists/";
    const option = {
        method: "post",
        auth: ""
    };
    const request = https.request(url, options, function(response) {
        response.on("data", function() {
            console.log(JSON.parse(data));
        });
    });
    request.write(jData);
    request.end();
});
app.listen(3000, function() {
    console.log("Server Çevrimiçi");
});

Upon trying to implement a function for the subscribe button to send user data to the hyper terminal when logging email name surname etc., I faced a redirection to 127.0.0.1. I suspect the issue lies between app.get and form direction, but I'm unsure how to fix it. Any suggestions or insights would be greatly appreciated.

Answer №1

Your printout is incorrect. Instead of what you are currently doing:

const mail = req.body.email;
const ilkad = req.body.fname;
const soyad = req.body.lname;

You should print the request data like this:

console.log(ilkad, soyad, email);

Another good practice is to use object destructuring in this way:

const {email, fname, lname} = req.body

and then print them out using:

console.log(fname, lname, email);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to correctly showcase dynamic pages in ExpressJS?

Within my app.js file, there exists an array of objects that is defined as follows: var people = [ {name: "Henrique Melo", username: "heenrique", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a121f1408130b0f1 ...

Whenever I try to log in using axios and my credentials are incorrect, I don't receive any response back in the catch block

I cannot receive any response when calling the login API from Node.js. In the frontend, I am handling the catch as well. How do I retrieve the Invalid Credentials message from the backend API if the credentials do not match? The code for my backend logi ...

Revamp the Design Layout of a Drag-and-Drop Tool

After experimenting with a drag and drop feature using jQuery, I discovered the following useful code snippet. Here's how it functions: $( "#sortable1, #sortable2" ).sortable({ connectWith: ".connectedSortable" }).disableSelection(); #so ...

What is the best way to ensure that a task is performed only once the DOM has finished loading following an AJAX request

<div id="mydiv"> ... <a id="my-ajax-link"> ... </a> ... ... <select id="my-selectmenu"> ... </select> ... </div> Upon clicking the 'my-ajax-link' link, it triggers an AJ ...

What is the best way to assign a JavaScript return value to a PHP variable?

Is it possible to capture the return value of a JavaScript function that checks if text boxes are empty and assign it to a PHP variable? I have successfully created a JavaScript function that returns false if any of the text boxes are empty, but now I ne ...

JavaScript Language Conversion Templating

I'm currently revamping the frontend for Facebook's internationalization XFBML tag, which has been nonfunctional for a while. I'm almost done with the updates but I have hit a roadblock: swapping out tokenized translations without losing dat ...

Manipulating layout with html5 VIDEO controls

I'm having an issue with the HTML5 video element. When I don't use "Controls," it displays with the border-radius as I specified. https://i.stack.imgur.com/KMEeJ.png However, when I add controls (which I need), an ugly border appears and overri ...

The mock-up functions flawlessly on my local machine, however, it is failing to run on the server with the JEST framework

Seeking assistance with unit testing using JEST framework for Node.js. Although the tests run successfully on my local machine, they fail to mock properly on both the server and my colleague's machine. After researching online, I came across suggestio ...

Is it necessary for NPM to execute scripts labeled as dependencies during the npm i command execution?

When npm i is run, should it execute the scripts named dependencies? I've observed this behavior in the latest version of Node (v19.8.1) and I'm curious if it's a bug. To replicate this, follow these steps: mkdir test cd test npm init -y T ...

Receiving "this" as an undefined value within the TypeScript class

Currently developing a rest api using express.js, typescript, and typeorm. Initially thought the issue was with AppDataSource, but it seems to be functioning properly. Below is my controller class: import { RequestWithBody } from '@utils/types/reque ...

Best Practices for Retrieving Data with Django - Post Requests

I'm attempting to use Ajax to send a JavaScript array to Django. Here's my code: document.getElementById('input-generate').onclick = () => { // Get the token const csrftoken = document.querySelector('[name=csrfmiddlewar ...

The online html page on the server is experiencing connectivity issues with Socket.io

I have successfully set up my node.js server on my local Windows machine and it is functioning properly. However, when I transfer the project to an online Linux server, socket.io fails to communicate between the server and the client (HTML page). Although ...

Incorporating a new element into a JavaScript array

I recently used a vue.js library that has a specific requirement for arrays in this exact format autocompleteItems: [ { text: "Python" }, { text: "HTML" }, { text: "CSS" }, { text: "React ...

I'm working on an Angular2 project and I'm looking for a way to concatenate all my JavaScript files that were created from TypeScript in Gulp and then include them in my index

How can I concatenate all JavaScript files generated from typescript in my Angular2 project with Gulp, and then add them to my index.html file? I am using Angular2, typescript, and gulp, but currently, I am not concatenating the javascript files it genera ...

Dismiss the Popover in Ionic 2

After opening a popover that redirects me to another page and then returning to the root page (popToRoot), I reload the data/dom upon an event and dismiss the popup once the json data is received from the server. Everything works smoothly with a lengthy ti ...

Can jq handle synchronous functions?

The usage of jq.run('.', '/path/to/file.json').then(console.log) appears to be causing asynchronous behavior, leading to the output being displayed as Promise { <pending> }. This delay in obtaining the result is problematic, promp ...

A structured HTML table featuring a secure header and stable left-hand columns, complete with knockout controls embedded in both the header and first

I'm facing a challenge with a customizable HTML table: Each row has a checkbox (knockout bound) to allow the user to determine if it should be included or not. The header columns also have checkboxes (knockout bound) to indicate if a particular ...

Encountering a type error while trying to create a document within a nested collection in Firebase Firestore

While trying to submit the form with property data, I encountered an error message: FirebaseError: Expected type 'za', but it was: a custom Ha object. There doesn't seem to be any information available online explaining what a Ha object is o ...

The div element is experiencing a resizing issue

I am currently working on the following HTML markup: <div class="card" style="height:100%"> <div class="controlPanelContainer"> <div class="card" style="background-color:yellow;height:200px"> </div> <div class= ...

utilizing Nuxt code in Elixir/Phoenix

Overview In my previous work, I combined frontend development with nuxt and backend support from elixir/phoenix, along with nginx for reverse proxy. Looking to enhance the performance of the system, my goal is now to migrate everything to Elixir/Phoenix. ...