Use node.js values in html file - javascript

I built 2 files. In the first file i fetch some data from a database with nodejs, in the second file a have a simple html markup where i want to insert the data from nodejs file (index.js). Which is the proper way to insert result which is used in console.log(result);, in my html file, in <h1 id="result"></h1>
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Test");
dbo.collection("users").find({}, { "name":"John" }).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
<!DOCTYPE html>
<html lang="en">
<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">
<script src="./index.js"></script>
<title>Document</title>
</head>
<body>
<h1 id="result"></h1>
</body>
</html>
So, how to insert result from index.js, in index.html file <h1 id="result"></h1>?

Related

Having an issue while running html file using Nodejs

I watched a tutorial to run node.js server for the very first time on your computer. Luckly I've created the server but got stck as I tried to show the html content on the exact same server.
This is my index.js file code -
const http = require("http");
const fs = require("fs");
const port = 8020;
const server = http.createServer((req, res) => {
res.writeHead(200, { "Contet-type": "text/html" });
fs.readFile("index.html", (err, data) => {
if (err) {
res.writeHead(404);
res.write("Error file not found");
} else {
res.writeHead(data);
}
res.end();
});
});
server.listen(port, function (err) {
if (err) {
console.log("Something went wrong");
} else {
console.log("server listening on port " + port);
}
});
And this is what I'm getting in the terminal -
PS C:\Users\Dell\OneDrive\Desktop\New folder> node index.js
server listening on port 8020
node:_http_server:343
throw new ERR_HTTP_INVALID_STATUS_CODE(originalStatusCode);
^
RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: <!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>This is my first nodeJs project</h1>
</body>
</html>
at new NodeError (node:internal/errors:393:5)
at ServerResponse.writeHead (node:_http_server:343:11)
at C:\Users\Dell\OneDrive\Desktop\New folder\index.js:12:11
at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read_file_context:68:3) {
code: 'ERR_HTTP_INVALID_STATUS_CODE'
}
Node.js v18.12.1
PS C:\Users\Dell\OneDrive\Desktop\New folder>
And not even the localhost, which is 8020 in this case, is not running on the browser.
I just want to know the mistakes here that I'm totally unaware with or something that I need to do in order to have my desired output.
You're writing the HTML to the header of the response:
res.writeHead(data);
you want:
res.end(data);
or
res.write(data);
res.end();

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>

No output with template-string

I try to use the npm qrcode API with express. When the user enters an address into a form, the QR-Code should be displayed on the website. I searched for a long time, but can't figure it out, since I don't understand what to loog for exactly.
I tried the following:
app.post('/ausgabe', async (req, res) => {
try {
res.setHeader('200', { 'Content-type': 'application/json' });
const eingabe = `'${req.body.address}'`;
const qrImage = await generateQR(eingabe);
console.log(qrImage);
const body = `<!DOCTYPE html>
<html lang="de">
<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>QR-Code</title>
</head>
<body>
<img ${qrImage} />
</body>
</html>`;
res.send(body);
} catch (err) {
res.status(404).json({
status: 'Fail',
message: err,
});
}
});
I console.logged 'qrImage' and it's there and correct, but there is nothing showing up in the HTML.
Thanks a lot,
TobiG

Posting data from a html form to SQL does not post

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();

Basic JS script does not want to load in the HTML file

I'm trying to get the most basic thing possible to work and can't figure out what I'm doing wrong.
my html file:
<!DOCTYPE html>
<html lang="en">
<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">
<script type="text/javascript" src="script.js"></script>
<title>This Is Just a Dummy App</title>
</head>
<body>
<button onclick="makeAlert()">Click here</button>
</body>
</html>
script.js, it's in the same directory as the HTML file
const makeAlert = () => { alert('Hey hey') };
The page does not want to load, period and there are no errors in the browser console.
UPDATE
This is part of Node.js app, without Express or anything and this is how it's configured to load HTML. I don't know if this is a factor here or not.
const http = require('http');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3001;
const server = http.createServer((req, res) => {
const url = req.url;
if(url === '/') {
res.writeHead(200, {
'Content-Type': 'text/html'
});
fs.readFile('./index.html', null, function (err, data) {
if (err) {
res.writeHead(404);
res.write('something went wrong');
} else {
res.write(data)
}
res.end();
})
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Works fine from a snippet, are you trying to run it from a server or just from the file system? Some browsers don't like running scripts from the file system. Get a development web server.
const makeAlert = () => { alert('Hey hey') };
<!DOCTYPE html>
<html lang="en">
<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>This Is Just a Dummy App</title>
</head>
<body>
<button onclick="makeAlert()">Click here</button>
</body>
</html>

Categories

Resources