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