Posting data from a html form to SQL does not post - javascript

I have a node.js web app, an SQL server, and I am working locally in visual studio code then syncing to azure.
I have a simple form on my home page which when I click post, should send the data to a table in my SQL database. However nothing is happening at all. I am redirected to the user page, and I get no errors, but I also get nothing in the console log, or anything posted to the table.
Here is what I have:
app.js
var express = require('express');
var app = express();
var mysql = require("mysql");
var bodyParser = require('body-parser');
var config = {
host: '',
user: '',
password: '',
database: '',
port: 3306,
ssl: true
};
var connection = new mysql.createConnection(config);
app.use('/node_modules', express.static(__dirname + '/node_modules'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/Template/views/home.html',function(req,res){
res.sendFile('home.html',{'root': __dirname + '/views'});
})
app.get('/Template/views/about.html',function(req,res){
res.sendFile('about.html',{'root': __dirname + '/views'});
})
app.get('/Template/views/user.html',function(req,res){
res.sendFile('user.html',{'root':__dirname + '/views'})
})
app.post('/Template/views/user.html', function(req, res){
var fName = req.body.first_name;
connection.query("INSERT INTO `Persons` (name) SET ?", fName.toString(), function(err, result) { function(err, result) {
if(err) throw err;
console.log("1 record inserted");
});
res.send('user.html',{'root':__dirname + '/views'})
});
app.listen(process.env.PORT);
home.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">
<meta name="description" content="">
<meta name="author" content="">
<title>Template</title>
<link href="../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<form action="/Template/views/user.html" name="formA">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name"> <br>
<input type="submit" value="submit">
</form>
</body>
</html>
Can anyone see what I am doing wrong here?

Try connection to the connection after defining it:
connection.connect();
then execute the query and finally close the connection with:
connection.end();

Add method='post' on your form.
<form action="/Template/views/user.html" method='post' name="formA">
And change the serverside code
app.get('/Template/views/user.html',function(req,res){
res.sendFile('user.html',{'root':__dirname + '/views'})
})
To:
app.post('/Template/views/user.html',function(req,res){
res.sendFile('user.html',{'root':__dirname + '/views'})
})
and start db connection like below.
var connection = new mysql.createConnection(config);
connection.connect();

Related

Error: Not Found The requested URL was not found on this server

I'm trying to send some html form data to a node js file using express. However as I submit the form I keep getting this error on the browser (I've tried different browsers and restarted the server every time):
Here's the code:
import mysql from 'mysql2';
import express from 'express';
import path from 'path';
let probes = [];
let measurements = [];
let to_country;
const app = express();
const __dirname = path.resolve();
app.use(express.urlencoded( {extended: true} ));
app.use(express.static(__dirname));
const con = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'probes&anchors'
});
con.connect((err)=>{
if(err){
console.log("Connection not proper");
}else{
console.log("connected");
}
});
app.post('/', async function(req,res){
to_country = req.body.to_country;
let sql = 'SELECT id FROM probes WHERE country=?';
await con.promise().query(sql, [req.body.from_country], (err, rows) => {
if (err) throw err;
probes.push(rows.id);
console.log('Probe id: ', rows.id);
})
console.log(probes);
con.end();
res.send("Loaded");
});
app.get('/', (req, res) => res.send('Hello World! From Node.js'));
app.listen(8000, () => console.log('Example app listening on port 8000!'));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch API Demo</title>
</head>
<body>
<form action="/" method="POST">
<label for="from_country">From:</label>
<select id="from_country" name="from_country">
<option>Country1</option>
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
</select>
<label for="to_country">To:</label>
<select id="to_country" name="to_country">
<option>Country2</option>
<option value="AF">Afghanistan</option>
</select>
<input type="submit" value="Latency?">
</form>
</body>
</html>
Both files are in the same directory.
I've modified Apache httpd.conf uncommenting two lines and adding the following line as shown here:
ProxyPass / http://localhost:8000
Can someone please help out? Any help is appreciated, thanks.
As I can see you are running apache server and node.js server on same port which requires some special configurations
you have to tell apache server explicitly to send (all or in some cases request coming from specific path) requests to node.js server (this technique is called reverse proxy technique)
this blog below might help you understand that
here
or here
EDIT
app.post('/', async function(req,res){
to_country = req.body.to_country;
let sql = 'SELECT id FROM probes WHERE country=?';
await con.promise().query(sql, [req.body.from_country], (err, rows) => {
if (err) throw err;
probes.push(rows.id);
console.log('Probe id: ', rows.id);
})
console.log(probes);
con.end();
res.send("Loaded");
});
can be simplified to ...
app.post('/', (req,res)=>{
to_country = req.body.to_country;
let sql = 'SELECT id FROM probes WHERE country=?';
con.query(sql, [req.body.from_country], (err, rows) => {
if (err) throw err;
else {
probes.push(rows.id);
console.log('Probe id: ', rows.id);
console.log(probes);
con.end();
res.send("Loaded");
}
})
});

How to access file accessed from server.js and display it in the html

I am creating a youtube video downloader with express, html, javascript and later on I want to switch to vue.js.
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">
<title>Document</title>
</head>
<body>
<h1>My Own Youtube downloader</h1>
<input class="URL-input" type="text" placeholder="enter...">
<button class="convert-button">Convert</button>
<script src="script.js"></script>
</body>
</html>
Script.js
var convertBtn = document.querySelector(".convert-button");
var URLinput = document.querySelector(".URL-input");
convertBtn.addEventListener("click", function () {
console.log("URL : ${URLinput.value}");
sendURL(URLinput.value);
});
function sendURL(URL) {
window.location.href = `http://localhost:4000/download?URL=${URL}`;
}
Server.js
const express = require("express");
const cors = require("cors");
const ytdl = require("ytdl-core");
const app = express();
app.use(cors());
app.listen(4000, () => {
console.log("Server is working at port 4000 !!");
});
app.get("/download", (req, res) => {
var URL = req.query.URL;
res.header("Content-Disposition", 'attachment; filename="video.mp4');
ytdl(URL, {
format: "mp4",
}).pipe(res);
});
Right now, everything works fine.
I just want to implement the functionality so you can see the youtube video on the frontend in the html.
Does anyone know how to implement this functionality?
PS: I rather don't use a database, only node and express for now
on server.js use
app.get("/download/:URL", (req, res) => {
var URL = req.params.URL;
res.header("Content-Disposition", 'attachment; filename="video.mp4');
ytdl(URL, {
format: "mp4",
}).pipe(res);
});
and main file, use
document.getElementById('video').src=`localhost:8080/download/${URL}`;
And in html file add
<video id="video" width="320" height="240" controls>
</video>

Send data from HTML form to Express API

I'm trying to build a login page for users and need to send the login info to my express server. I'm not too sure about how to call the api for my server and send the information across though.
Right now I get a 405 error method not allowed when I try to submit the form by clicking on the button.
index.html:
<!DOCTYPE html>
<html land="en">
<head>
<meta charset="UTF-8">
<title>Home page</title>
<script src="../app.js"></script>
</head>
<body>
To login
</body>
</html>
login.html:
<!DOCTYPE html>
<html land="en">
<head>
<meta charset="UTF-8">
<title>Login page</title><br><br>
<script src="../app.js"></script>
</head>
<body>
<form id="login-form" method="post" action="/login">
<input type="text" name="username" id="username-field" placeholder="Username" required><br><br>
<!-- TODO: Change type to "password" -->
<input type="text" name="password" id="password-field" placeholder="Password" required><br><br>
<input type="submit" value="Login" id="login-form-submit">
</form>
</body>
</html>
app.js:
const express = require('express')
var bodyParser = require('body-parser')
var port = process.env.PORT || 3000;
var app = express();
app.use(express.json());
app.use(express.urlencoded({"extended": true}));
app.get('/', function (req, res) {
res.render(__dirname + '/views/index.html');
});
app.post('/login', function (req, res) {
res.statusCode = 200;
res.send({ 'body': req.body });
});
// Listen on port 3000, IP defaults to 127.0.0.1
app.listen(port, () => {
console.log('Server listening at http://127.0.0.1:' + port + '/');
});
You can do it using javascript. Add this to your login.html file
<script type="text/javascript" >
async function login(){
// Get values from FORM
let username = document.getElementById("username-field")
let password = document.getElementById("password-field")
// Body payload
let body = { username, password }
// Fetch options
let option = {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json'
}
}
// Call /login as POST and wait for reply
const response = await fetch(`/login`, options)
const json = await response.json()
// Use json response
alert(json)
}
document.getElementById("login-form-submit").addEventListener("click", login);
</script>
In order for the server to be properly up, you need to make sure you run it as node app.js instead of adding it to the html file.
UPDATE:
Check out this repo for a working solution : https://github.com/rui-costa/stackoverflow-68238492

Nodejs subscribe button redirects me to 127.0.0.1

When I click the subscribe button it redirects my page to 127.0.0.1 and nothing appears in console.log. Why is that
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");
});
I just wanted to apply the subscribe button a function to send data to the hyper terminal when the user logs mail name surname etc. but when I click it redirects me to 127.0.0.1 which is local folder. and I am almost sure that there is something wrong between app.get and form direction but I don't know how to solve this problem. I know it is a long post sorry for that but I really appreciate some help. thank you.
You are printing the wrong variables. Since you do this:
const mail = req.body.email;
const ilkad = req.body.fname;
const soyad = req.body.lname;
you should print the data from request by:
console.log(ilkad, soyad, email);
Also, a good practice is using the object destructuring like this:
const {email, fname, lname} = req.body
and then use:
console.log(fname, lname, email);

POST-Request doesn't get forwarded via http-proxy

I am trying to build a reverse-proxy server where the url has an id (?id=1) and the proxy server redirects to port 8000 + id!
So it works when i go to the right port directly, but when I use the proxy the browser-tab loads endlessly.
It also works with GET-Request, but POST-Request don't work!
This is my reversed-proxy:
const express = require(`express`);
const proxy = require(`http-proxy`);
const ps = proxy.createProxyServer();
const app = express();
app.listen(8000);
app.all(`*`, (req, res) => {
if (req.query.id) {
try { const id = parseInt(req.query.id);
ps.web(req, res, { target: `${req.protocol}://${req.hostname}:${8000+id}` });
} catch (err) { res.redirect(redirectUrl); }
} else { res.redirect(redirectUrl); }
});
ps.on(`error`, (err, req, res) => {
res.redirect(redirectUrl);
});
This is my website running on port 8001:
app.get(`*`, (req, res) => {
res.render(`index`, {
link: `?id=1`,
name: `name`,
value: `value`,
text: `text`,
});
});
app.post(`*`, (req, res) => {
res.render(`index`, {
link: `?id=1`,
name: `name`,
value: `value`,
text: `text`,
});
});
And this is my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action={{link}} method="POST">
<button name={{name}} value={{value}}>
<h4> {{text}} </h4>
</button>
</form>
</body>
</html>
By the way i am also using express-handlebars so the {{}} in the html is for that!
ty for any ideas :)

Categories

Resources