I have a bit of code that should load a page and show an image(from server storage), that sometimes changes(is replaced by another image with the same name).
main.js:
const app = express();
const ejs = require('ejs');
var fs = require('fs');
const port = 8000;
// Render index.ejs file
app.get('/', function (req, res) {
// Render page using renderFile method
ejs.renderFile('index.ejs', {},
{}, function (err, template) {
if (err) {
throw err;
} else {
res.end(template);
}
});
});
// Server setup
app.listen(port, function (error) {
if (error)
throw error;
else
console.log("Server is running");
});
index.ejs:
<html lang="en">
<head>
<title>Fasole LIVE</title>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
</head>
<body>
<img src="live.png" class="live" id="live">
<script>
while(true)
{document.getElementById("live").src("live.png")}
</script>
</body>
</html>
What am I doing wrong?
Related
I have the following app with express/socket.io (the app is listening and live without any errors). When I http-request it I get the following error:
GET http://localhost:3030/socket.io/1/?t=1630097351846 404 (Not Found)
And on the socket.io reponse http://localhost:3030/socket.io at I get:
Cannot GET /socket.io
Please help !!
const socket=io.connect('http://localhost:3030/');
//const { Socket } = require("socket.io");
const videoGrid=document.getElementById('video-grid');
const myVideo=document.createElement('video');
myVideo.muted=true;
let myVideoStream
navigator.mediaDevices.getUserMedia({
video:true,
audio:true
}).then(stream=>{
myVideoStream=stream;
addVideoStream(myVideo,stream);
})
// socket.emit('join-room');
const addVideoStream=(video,stream)=>{
video.srcObject=stream;
video.addEventListener('loadedmetadata',()=>{
video.play();
})
videoGrid.append(video);
}
const express=require('express');
const app=express();
const server=require('http').Server(app);
const {v4: uuidv4}= require('uuid');
const io=require('socket.io-client')(server);
//import { io } from "socket.io-client";
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.get('/',(req,res)=>{
res.redirect(`/${uuidv4()}`);
})
app.get('/:room',(req,res)=>{
res.render('room',{roomId :req.params.room});
})
io.on('connection',socket=>{
socket.on('join-room',()=>{
console.log("Room Joined");
})
})
//now need to import socket.io in script.js
// server.listen(app.get('3030'));
app.listen(3030);
<!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>Zoom RJ</title>
<link rel="stylesheet" href="style.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
<!-- <script src="/node_modules/socket.io/client-dist/socket.io.js"></script> -->
</head>
<body>
<div id="video-grid">
</div>
<script src="script.js"></script>
</body>
</html>
Losing my mind here. I feel like I have the paths correct but for some reason my script file isn't loading/working. When I move the code to the app.js it prints out what I want to the console and works just fine but when I have it in the scripts file, it does nothing. I cant seem to find the problem.
app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(express.static(`${__dirname}/public`));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
const rootRoute = require('./routes/index')
app.use('/', rootRoute);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log('server is running')
});
HTML page
<!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>In Your Words</title>
<link rel="stylesheet" href="/stylesheets/app.css">
</head>
<body>
<script type="text/javascript" src="/scripts/logic.js"></script>
</body>
</html>
script page
const generateInputs = () => {
let randomNumber = Math.floor(Math.random() * 20);
console.log(randomNumber)
}
generateInputs();
I writirng server in Express to posibility GET and POST. In Insomnia I get and post valid data.
This is code my REST.
const express = require('express');
const app = express();
const port = 3000;
var cors = require('cors');
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({extended: true}));
let myValue = 1;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
//GET
app.get('/get', (req, res) => {
return res.json({"wartosc": myValue})
});
//POST
app.post('/post', function (req, res) {
myValue = req.body.value;
console.log(req.body)
return res.json({"wartosc": myValue});
});
Then I creaeted page with two input will be used to call the GET and POST methods of our REST server.
async function getMethod() {
let inputValue = document.getElementById("inputValue").value;
const responseGet = await fetch('http://localhost:3000/get');
const myJsonGet = await responseGet.json();
//console.log(JSON.stringify(myJsonGet));
document.getElementById("inputValue").value = myJsonGet.wartosc;
}
async function postMethod(){
let inputValue = document.getElementById("inputValue").value;
let responsePost = await fetch('http://localhost:3000/post', {
method: 'POST',
body: {'value' : JSON.stringify(inputValue)}
});
}
<!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>Document</title>
</head>
<body>
<input type="text" id="inputValue">
<button onclick="getMethod()"> GET</button>
<button onclick="postMethod()">POST</button>
<script src="script.js"></script>
</body>
</html>
When I do get , I get the correct value, but when I change the value and send a post, the server prints undefined.
I don't know why, will you try to help me?
In your script.js postMethod() you should stringify the entire body:
body: JSON.stringify({'value' : inputValue})
Ideally you use querystring.stringify instead but this should also work fine.
Alternatively, you can just leave out the entire script.js with the async stuff.
Instead try with using a form and name="value". You can change the form action and method per button.
<!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>Document</title>
</head>
<body>
<form method="GET" action="http://localhost:3000/get">
<input type="text" id="value" name="value">
<button type="submit">GET</button>
<button type="submit" formmethod="post" formaction="http://localhost:3000/post">POST</button>
</form>
</body>
</html>
I did some changes to make it work on CodeSandbox (example). Everything works.
const express = require("express");
const app = express();
const port = 3000;
var cors = require("cors");
const rand = () =>
Math.random()
.toString(36)
.substr(2);
app.use(express.static("public"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
//GET
app.get("/get", (req, res) => {
return res.json({ getval: rand() });
});
//POST
app.post("/post", function(req, res) {
return res.json({ postval: `${rand()}:${req.body.value}` });
});
I put HTML and JavaScript files in the public directory.
async function getMethod() {
const responseGet = await fetch("/get");
const myJsonGet = await responseGet.json();
document.getElementById("inputValue").value = myJsonGet.getval;
}
async function postMethod() {
let inputValue = document.getElementById("inputValue").value;
let options = {
method: "POST",
body: JSON.stringify({ value: inputValue }),
headers: {
"Content-Type": "application/json"
}
};
let responsePost = await fetch("/post", options);
let myJsonPost = await responsePost.json();
document.getElementById("inputValue").value = myJsonPost.postval;
}
Both when you send JSON data via GET and POST, you must extract it with response.json(). In addition, when submitting POST data, you must set a header that is JSON. Without it, the server will not recognize that the transmitted data is in this format.
I need to pass a variable from a NodeJS file to a rendered html file. How to do that?
Here below what I had tried
Nodejs code
const loginRouter= express.Router();
const config= require('../config/config.json');
loginRouter.get('/', (req,res)=>{
res.render(path.dirname(__dirname)+'/views/login.html',{version:config.version});
//res.json('done')
});
HTML Code
<label style="font-size:10px;float: right;"><%= version %></label>
Current Result:-
Nothing is coming
Expected Result:-
<label style="font-size:10px;float: right;">3.9</label>
I have set this version number in my config which I have imported in my login.js, but still, I am not getting the output. Does anyone have any idea about it?
If you don't want to use a templating engine like ejs or pug then you can just send a get request with axios or fetch to your node server and send a response.
Here's a sample on how you can do it. Change it according to your needs.
index.html
<!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>Document</title>
</head>
<body>
<h1 id="title">My page</h1>
<script>
fetch('http://localhost:5000/version').then(function(response) {
return response.json();
}).then(function(myJson) {
document.getElementById('title').innerHTML = myJson;
});
</script>
</body>
</html>
server.js
const express = require('express');
const app = express();
const PORT = 5000;
app.get('/', (req, res) => {
res.sendFile('index.html', {root: __dirname });
});
app.get('/version', (req, res) => {
const myVersion = 'My version is 0.5';
res.json(myVersion);
});
app.listen(PORT, () => {
console.log(`Server running on PORT ${PORT}`);
});
I am new to node.js and I m trying to play around with GraphicsMagic. I have installed GraphicsMagic in my windows pc and also installed gm module with npm install. I am able to get fullsize image but not able to create thumbs with the following code. can anyone help me to go in correct direction?
var express = require('express');
var app = express();
var fs = require('fs');
var gm = require('gm');
app.configure(function () {
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
});
app.listen(8080);
console.log("App listening on port 8080");
app.post('/upload', function (req, res) {
fs.readFile(req.files.image.path, function (err, data) {
var imageName = req.files.image.name;
if (!imageName) {
console.log("There was an error");
res.redirect("/");
res.end();
} else {
var newPath = __dirname + "/uploads/fullsize/" + imageName;
var thumbPath = __dirname + "/uploads/thumbs/" + imageName;
fs.writeFile(newPath, data, function (err) {
gm(newPath)
.resize(240, 240)
.noProfile()
.write(thumbPath, function (err) {
if (!err) console.log('done');
res.redirect("/uploads/thumbs/"+imageName);
});
});
}
});
});
app.get('/uploads/thumbs/:file', function (req, res) {
file = req.params.file;
var img = fs.readFileSync(__dirname + "/uploads/thumbs/" + file);
res.writeHead(200, {'Content-Type': 'image/jpg' });
res.end(img, 'binary');
});
app.get('*', function (req, res) {
res.sendfile('./views/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>