Email Form Application: Utilizing NodeJs and Express - Error: URL Not Found /

I'm encountering a "cannot GET" error whenever I try to run my application on a live server using VS Code. My assumption is that the issue lies within my routing configuration, but I'm struggling to identify the exact problem. Any assistance would be greatly appreciated! <3

The objective is to send a POST request containing the user's email input from a form element once the application is complete.

app.js

const express = require('express');
const request = require('request');
const bodyParser = require('body-parser');
const path = require('path');

const app = express();

// Middleware
app.use(express.json());

app.use(bodyParser.urlencoded({extended: false}));

console.log("The directory is:", (path.join(__dirname, '/site')));

app.use(express.static(path.join(__dirname, '/site')));

app.post('/', (req, res) => {
    console.log('hey!');
});

app.listen(5000, console.log('Server started!'))

landing.html

<form action="/subscribe" method="POST">
  <div class="newsletter-form-grp">
     <i class="far fa-envelope"></i>
    <input name="email" id="email" required pattern="[a-z0-9.%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" type="email" placeholder="Enter your email...">
  </div>
  <button id="cta">SUBSCRIBE <i class="fas fa-paper-plane"></i></button>
</form>

JS Code within landing.html

<script>
   // Form submission
   let cta = document.getElementById('cta');
   let email = document.getElementById('email').value;
   let status = document.getElementById('status');

   cta.addEventListener('click', (event) => {
       event.preventDefault();

       if(this.email.value == null || this.email.value == "") {
             status.classList.add('statusShow');
       } else {
              let fetchData = {
                 method: 'POST',
                 body: JSON.stringify({email: this.email.value, js: true}),
                 headers: {"Content-Type": "application/json"}
              }

              fetch('/subscribe', fetchData)
                 .then(res => {
                   if(res.ok) {
                                // yay
                   } else {
                      status.classList.add('statusShow');
                   }
                })
       }
    });
</script>

JSON Package

{
  "name": "Main",
  "version": "1.0.0",
  "description": "",
  "main": "site/js/app.js",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "index": "^0.4.0",
    "request": "^2.88.2"
  },
  "devDependencies": {
    "nodemon": "^2.0.15"
  },
  "scripts": {
    "serve": "node app",
    "dev": "nodemon app"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Project Tree: https://i.sstatic.net/LzVHv.jpg

Answer №1

Your landing page, landing.html, is a static file located in the site folder. However, you do not currently have a GET route defined in your Express server to serve this page. To access it from your browser, you will need to use the following URL: http://localhost:5000/landing.html.

The form on your page is coded as follows:

<form action='/subscribe' action='POST'>
. Therefore, you must define a POST route in Express like this:

app.post("/subscribe", (req, res) => {
   console.log("hey!");
   res.send("got it!"); 
});

Additionally, there is no element with the id 'status' in your HTML. This means that the click event code for your subscribe button will result in an error.

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 process for accepting user input if their username remains the same?

I've been grappling with what logic to implement in this scenario. I want the user to be able to update their information, but an issue has arisen. What if a user wishes to change their email but keep the same username? As it stands, the username is ...

Executing an .exe file directly through a web browser (using any method)

Currently, I am managing various devices within a local network through a page. However, there are certain advanced settings that can only be accessed by using an .exe file located on the computer where the configuration page is run. I would like to stream ...

Switching between numerical and alphabetical input using JQuery

How can I switch between allowing character and numeric input in a textbox? I currently have a JQuery function that restricts input to numbers only $('.numeric').on('input', function (event) { this.value = this.value.replace(/[^0 ...

AJAX not showing validation error message

For the past two days, I've been grappling with an issue and can't seem to pinpoint where it's coming from. After leaving the textbox, the Ajax call functions correctly and returns results as either true or false, triggering the success fun ...

Placing an emblem after the header wording

Within my h1 tag, I have a header text that I would like to display alongside a small icon on the right side. The length of the text can vary, which presents a challenge in alignment. I attempted to use a background image with no repeat, but it ends up p ...

Error message: Component is unable to access the $store property because it is undefined

After doing extensive research and reading numerous similar questions on various platforms, I am still unable to resolve my issue. I have a component containing a login form that triggers a method to dispatch a $store action for logging in the user via fi ...

Tips for serving a JSON text file to a client-side AJAX request from a Node.js server

I have a node.js web app running on an AWS Ubuntu server. The json data from an API is stored locally on the server in a file named data.json. My goal is to load this data via AJAX and display it on the client-side HTML. Below is my project directory str ...

Calculate the difference and sum of time values with varying signs in JavaScript

-12:00 - 5:30 => -6:30 -2:00 - 5:30 => 3:30 00:00 - 5:30 => -5:30 6:00 - 2:30 => 3:30 I am interested in subtracting time with both positive and negative indices. let myCountries = [ { countryName: "NewZealand", ...

What could be causing the error where axios.get is not functioning properly?

Recently, I embarked on a journey to familiarize myself with working with packages and npm. My first step was to import axios for a simple http request. Initially, I set up the project using npm init successfully. However, I encountered my first roadbloc ...

Executing React Fetch API Twice upon loading the page

Double-fetching Issue with React Fetch API on Initial Page Load import React, { useState, useEffect } from 'react' import axios from 'axios'; import { Grid, Paper, TextField } from '@mui/material' import PersonOut ...

Cutting an in-memory Base64 PNG using ONLY JavaScript on the client side without relying on canvas

Scenario: Working with JavaScript in a SDK environment, either on node.js or a browser. Situation: I have a base64 string containing a PNG image encoded using base64 (extracted from selenium webdriver's takeScreenshot function). Inquiry: How can I c ...

Challenges encountered while running npm install

Encountered an error when trying to use the npm install command: npm ERR! code ENOTFOUND npm ERR! errno ENOTFOUND npm ERR! network request to https://registry.npmjs.org/@types/react-dom/-/react-dom-16.0.11.tgz failed, reason: getaddrinfo ENOTFOUND registr ...

Using the Mongoose library in the API directory of a Next.js 13.2 application results in a syntax error

Inside hello.js import connectMongo from '../../../util/connectDB'; import UserModel from '../../../models/UserModel'; import { NextResponse } from 'next/server' export async function GET(request) { return NextResponse.json ...

Are moment.js and moment.php interchangeable?

Recently, I developed a JavaScript script utilizing moment.js and I am looking to mirror it using a cron job in PHP. In my search for moment.js equivalents in PHP, I came across this https://github.com/fightbulc/moment.php ...

establishing multiple connections to mongodb using node.js

The following code demonstrates how to connect to MongoDB: var settings = { db: { native_parser: true }, server: { poolSize: 5 }, replset: { rs_name: 'myReplicaSetName' }, user: 'myUserName', pass: 'm ...

Sort with AngularJS: orderBy multiple fields, with just one in reverse

Currently, I am faced with the challenge of filtering data based on two variables: score and name (score first, followed by name). This task involves various games, some of which have scores in reverse order (like golf) while others maintain a normal scor ...

Choose three different images and one corresponding word from a JavaScript array to be displayed individually on the screen in separate div containers

I am in the process of developing a web game that will showcase 3 images on the screen, and the player must select the image that corresponds to the displayed word. I have successfully created a JavaScript array containing the images and words retrieved fr ...

Variety of formatting options for menu items when the menu is in its collapsed state

I am working with a Bootstrap nav-bar that collapses into a button by default. Within my nav-bar, I have opted for images instead of text links. However, when the nav-bar is collapsed, I would like these images to be smaller in size. Is there a way to cu ...

What is the most effective method for establishing a notification system?

My PHP-based CMS includes internal messaging functionality. While currently I can receive notifications for new messages upon page refresh, I am looking to implement real-time notifications similar to those on Facebook. What would be the most efficient ap ...

Utilize a variable within a regular expression

Can the variable label be used inside a regex like this? const label = 'test' If I have the regex: { name: /test/i } Is it possible to use the variable label inside the regex, in the following way? { name: `/${label}/i` } What do you think? ...