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

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>

Related

Error crbug/1173575, non-JS module files deprecated

I run this code and when I go to ws://localhost:1337 I get this error, how can I fix it?
(I tried different ways on the internet but none of them solved my problem)
error in chrome : crbug/1173575, non-JS module files deprecated.
import { createServer } from "http";
const PORT = 1337;
const server = createServer((request, response) => {
response.writeHead(200);
response.end('hello world,');
}).listen(PORT, () => console.log(`server listening on port ${PORT}`));
server.on('upgrade', (req, socket, head) => {
console.log({
req,
socket,
head
});
});
;[
"uncaughtException",
"unhandledRejection"
].forEach(event =>
process.on(event, (err) => {
console.error(`something bad happened: ${event}, msg:${err.stack || err}`);
})
);
<!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>Web Socket</title>
</head>
<body>
<!-- 1 -->
<p>Message</p>
<output id="messages"></output>
<script>
const messages = document.getElementById('messages');
// 2
const socket = new WebSocket('ws://localhost:1337');
// 3
socket.onopen = (event) => console.log('WebSocket is connected!');
//4
socket.onmessage = (msg) => {
const message = msg.data
console.log('I got a message!', message);
messages.innerHTML += `<br /> ${message}`;
}
// 5
socket.onerror = (error) => console.log(`WebSocket error`, error);
// 6
socket.onclose = (event) => console.log(`Disconnected from the WebSocket server`);
</script>
</body>
</html>
My JS code is in a file called server.mjs.

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

Use node.js values in html file

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>?

Categories

Resources