No output with template-string - javascript

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

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.

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>

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

Unknown error occurring when send put and delete requests (posts are fine)

So When i send a post request to my end point Everything works. However when i send put and delete requests i got problems in the response. Here is my code for one of my endpoints (put)
THE RESPONSE EXACTLY:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot PUT /api/auth/username</pre>
</body>
</html>
Code:
router.put('/username/:id', asyncMiddleware(async (req, res) => {
const user = await User.findByIdAndUpdate(req.params.id, {username: req.body.username, email: req.body.email, password: req.body.password}, {new: true})
if (!user) return res.status(404).send('User not found.')
res.send('User sucessfully updated.')
}))
Please help this BUG IS A PAIN.

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