Submit value from HTML form to Node-js using post request - javascript

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>

Related

Access Data During HTML form Post Back

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

How to run html file on localhost3000? [duplicate]

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

Server program using Get and Post

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.

discord webhook help javascript

I am trying post a Webhook using javascript. My goal is to allow the user to type their Webhook URL, and when they click "send", it should send my Webhook message.
I am new to Javascript and not sure what I am doing wrong!
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>Document</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="background">
<input type="text" id="input" placeholder="paste webhook here">
<button id="send" onclick="sendMessage()">send</button>
</div>
</body>
<script src="index.js"></script>
</html>
Javascript:
function sendMessage() {
let grabData = document.getElementById("input");
var request = new XMLHttpRequest();
request.open("POST", grabData);
request.setRequestHeader('Content-type', 'application/json');
var myEmbed = {
title: "Test Successful! 🥳",
color: hexToDecimal("#2A67E8")
}
var params = {
username: "objexive",
avatar_url: "https://i.ibb.co/7X9szNY/exhbition-webhookicon1.png",
embeds: [ myEmbed ]
}
request.send(JSON.stringify(params));
// function that converts a color HEX to a valid Discord color
function hexToDecimal(hex) {
return parseInt(hex.replace("#",""), 16)
}
}
for anyone that has the problem, it was a very simple fix. add .value to "grabData"

Nothing is being shown while there's no error. The code is working fine

app.js
angular.module('app', ['ionic', 'ui.router'])
.config(('$urlRouterProvider', '$stateProvider', function($urlRouterProvider,$stateProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('view',{
url:'/',
templateUrl:'js/components/view/view32.html',
controller:'viewCtrl'
})
}))
server.js
var express= require('express');
var mongoose = require('mongoose');
var bodyParser=require('body-parser');
var cors= require('cors');
var app= express();
var multiparty= require('connect-multiparty');
var multipartMiddleware= multiparty();
var viewController=require('./controllers/viewController');
var shareController=require('./controllers/shareController');
var configs = require('./configs/config.js');
configs.setConfigs();
mongoose.connect(process.env.MONGO_URL);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(multipartMiddleware);
app.use(cors());
app.use('/app', express.static(__dirname+ '/app'));
app.get('/',function(req,res){
res.sendFile(__dirname +'/index.html');
});
app.post('/share', multipartMiddleware, shareController.shareNewPicture);
app.get('/getNewPhoto', viewController.getNewPhoto);
/*app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Methods','POST, GET, OPTIONS, PUT');
next();
});*/
var port = 8080 || process.env.PORT;
app.listen(port, function(){
console.log('Server Started '+ port);
});
view.js
(function(window, angular, undefined)
{
angular.module('app')
.controller('viewCtrl',['$scope','$state','$http',function($scope,$state,$http)
{
$scope.pics=[];
$http.get('http://localhost:8080/getNewPhoto').then(function(response){
$scope.pics=response.data;
console.log('Hello photos are here');
},function(err)
{
console.error("There's an error"+err);
})
}])
})(window,window.angular)
The index.html where I'm calling views
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link rel="manifest" href="manifest.json">
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.min.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/components/view/view.js"></script>
</head>
<body ng-app="app">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title"></h1>
</ion-header-bar>
<ion-content>
<div ui-view>
</div>
</ion-content>
</ion-pane>
</body>
</html>
Here's the view.html which i want to show
view1.html
<div>
<div ng-repeat='pics in pic'>
<p> This is the view.html</p>
<img ng-src={{pic.url}}/>
</div>
</div>
There's nothing happening with view. I'm trying to get the view of photos but its not showing any error or any view. Please if anybody could help!!
In ajax you write :
$scope.pics=response.data;
but in your ng-repeat your write:
<div ng-repeat='pics in pic'>
change to
<div ng-repeat='pic in pics'>

Categories