I'm re-teaching myself web development after 15-years of no web development. I'm currently learning Node.js and ExpressJS. I have a registration form on index.html. I'm trying to transfer the data entered to a form on response.html. When I click Submit, the form is posted to response.html. In response.html under Devtools I see the data under Payload. How do I access this data so I can populate the form using client-side JavaScript on response.html?
File Structure
server.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(express.static(`${__dirname}/static`));
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
});
app.post('/response.html', urlencodedParser, function (req, res) {
res.sendFile(`${__dirname}/static/response.html`);
});
var server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log(`Server is listening onhttp://${host}:${port}`);
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration</title>
</head>
<body>
<h1>Registration Form</h1>
<form action="/response.html" method="POST">
<label>First Name: <input type="text" name="first_name"><br></label>
<label>Last Name: <input type="text" name="last_name"></label>
<input type="submit" value="Submit">
</body>
</html>
response.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Verify</title>
</head>
<body>
<h1>Verify Data</h1>
<form action="/process_final" method="POST">
<label>First Name: <input type="text" name="first_name"><br></label>
<label>Last Name: <input type="text" name="last_name"></label>
<input type="submit" value="Submit">
</body>
<button id='getHeaders' type='button'>Get Headers</button>
<script src='./response.js'></script>
</body>
</html>
My thinking is this will unload some of the processing from the server. I am aware of templating engines such as ejs and handlbars. I'm also aware of session storage and local storage. I'm reluctant to use storage since there may be sensitive data used in the final product. Attached are screenshots of the folder structure and html files. Also included is the html code and server.js.
After seven hours of searching the web, my conclusion is this is not possible. From what I read accessing the header information using client-side JavaScript is not possible. There are a few exceptions such as User Agent though.
You can access the data in the server side using req.body.first_name and req.body.last_name or you can destructure it like const { firstname, lastname } = req.body
Related
I'm making a small programm here in HTML/JS and I'm getting an error I've never seen before.
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
This is my code.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div>
<label for="lgn">Login:</label>
<input name="lgn" type="text" class="login-text">
</div>
<div>
<label for="psswrt">Password:</label>
<input name="psswrt" type="password" class="password-text">
</div>
<button class="submit-button">Submit</button>
<div class="answer-display"></div>
<script src="script.js"></script>
</body>
</html>
script.js
let loginData = ["test login"]
let passwordData = []
const lgn = document.querySelector(".login-text")
const pswrt = document.querySelector(".password-text")
const btn = document.querySelector(".submit-button")
const ansr = document.querySelector(".answer-display")
Please help
This question already has answers here:
Serve HTML with Express
(3 answers)
Closed 3 months ago.
I have all my .js files and html linked to my server file. but when I lunch localhost3000, I get "cannot get/"
I tried anything I though could be helpful but couldn't fix the problem. Anyone knows how to fix it?
I have this for my server side
const express = require('express');
const app = express();
app.listen(3000, () => console.log('listening at port 3000!'));
app.use(express.static('codefreeze.html'));
and I have this for client side
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="codefreeze.js"></script>
<link rel="stylesheet" href="codefreeze.css">
<link href = "https://fonts.googleapis.com/css?family=Schoolbell&v1" rel="stylesheet">
<title>DIARY</title>
</head>
<body onload="Name()">
<h1>HELLO!</h1>
<p>Welcome <span id="name"></span></p>
<p id="date"></p>
<script>
document.getElementById("date").innerHTML = DATE();
</script>
<div id="user">
<label id="lbl1">Passage #1</label><br>
<textarea id="psg1" rows="10" cols="30"></textarea><br>
</div>
<button id="save" onclick="save()">SAVE</button>
<button id="add" onclick="add()">ADD</button>
<button id="delete" onclick="del()">DELETE</button>
</body>
</html>
I know something I'm doing is wrong but I cannot seem to find what.
app.get("/", (req, res) => {
response.sendFile(*your file path*);
});
This should work
My index.html page
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome Home</title>
</head>
<body>
Please Login Here!
</body>
</html>
My login.html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example of Login Form</title>
</head>
<body>
<form action="login.html" method="post">
Username:<br>
<input type="text" name="username" placeholder="Username" required><br><br>
Password:<br>
<input type="password" name="password" placeholder="Password" required><br><br>
<input type="submit" value="login">
</form>
</body>
</html>
My server page
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}))
app.get('/',(req,res)=>{
res.sendFile(__dirname+'/static/index.html');
})
app.get('/login',(req,res)=>{
res.sendFile(__dirname+"/static/"+"login.html");
})
app.post('/login',(req,res)=>{
let username = req.body.username;
let password = req.body.password;
res.send(`Username : ${username} Password: ${password}`)
})
const port = 3000;
app.listen(port,()=>console.log(`This app is listening on port : ${port}`));
I am new to node.js.When I run using node server.js, I get Cannot GET /login.html.I can get into index.html. Why I am getting this.
This is my directory
. ├── package.json
. ├── server.js
. └── static
. . ├── index.html
. . └── login.html
try using express.static() middleware.
you can read more about serving static files here
ex:
const express = require('express');
const path=require('path');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(path.join(__dirname,'static')));//use folder containing your html files
app.get('/',(req,res)=>{
res.sendFile('static/index.html');
})
app.get('/login',(req,res)=>{
res.sendFile("static/login.html");
})
app.post('/login',(req,res)=>{
let username = req.body.username;
let password = req.body.password;
res.send(`Username : ${username} Password: ${password}`)
})
const port = 3000;
app.listen(port,()=>console.log(`This app is listening on port : ${port}`));
It appears that your request is to
/login.html
but there is no such route set up in your server.
There is a route
/login
which sends the file login.html, so, to hit that route, it would be a url that looks like:
http://localhost:3000/login
NOT
http://localhost:3000/login.html
Alternatively, set up static middleware to serve static files from a specified directory.
I am fairly new coding in JavaScript and web development, and I was wondering if there was any way to input an alert through an HTML text form and have it run on another page after it has been submitted, right now this is what I have.
index.html
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>form</title>
</head>
<body>
<form action="results.html" method="GET">
<div>
<label>Name</label> <input style="width: 400px;" size=400px type="text" name="name" id="name" placeholder="username" required>
</div>
<button type="reset">Reset</button>
<button type="submit">Submit</button>
</form>
</body>
results.html
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Results</title>
</head>
<body>
<div id="results"></div>
Back to Form
<script>
const resultsList = document.getElementById('results')
new URLSearchParams(window.location.search).forEach((value,
name) => {
resultsList.append(`${name}: ${value}`)
resultsList.append(document.createElement('br'))
})
</script>
</body>
I want to get something like this
My input
What I am trying to achieve
You have to receive a variable that you send with the "get" method.
With the window.location object. This code gives you GET without the question mark.
let myTextAlert = window.location.search.substr(1)
(You can use split() method to get rid of &)
Next in Your div or insert js:
<div id="results">
<script>
alert("This page Says:" + myTextAlert);
</script>
</div>
I want to submit input value from HTML form to Node.js
we have the following files:
app.js
index
output: console.log(“post request made”);
What should I do?
const express = require('express')
const app = express()
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}))
// app.use(express.urlencoded({
// extended: true
// }))
app.post('/submit-form', (req, res) => {
const username = req.body.username
console.log('HASAN');
res.end();
})
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="POST" action="/submit-form">
<input type="text" name="username" />
<input type="submit" />
</form>
</body>
</html>