How to Fetch multiple images in nodeJS? - html

So, problem is i have two jpg images you can see in HTML code. But only download.jpg is showing not lenovo.jpg but both are showing in the req.url
console image is attached and output is also attached.
HTML output
Console ScreenShot
this is my js file
//creating web server
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function(req,res){
if(req.url === "/"){
fs.readFile('./public/index.html',"UTF-8", function(err,html){
res.writeHead(200,{'content-type': 'text/html'});
res.end(html);
});
}
else if(req.url.match("\.css$")){
var cssPath = path.join(__dirname, '/public', req.url);
var fileStream = fs.createReadStream(cssPath, "UTF-8");
res.writeHead(200, {'content-type': 'text/css'});
fileStream.pipe(res);
}
else if(req.url.match("\.jpg$")){
var imagePath = path.join(__dirname,'/public',req.url);
var fileStream = fs.createReadStream(imagePath);
res.writeHead(200,{'content-type': 'image/jpg'});
fileStream.pipe(res);
}
console.log(req.url);
}).listen(3000);
My Html
<!DOCTYPE html>
<html>
<head>
<!-- <meta charset="utf-8"> -->
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My HTML Page</title>
<link rel="stylesheet" type="text/css" href="./css/base.css">
</head>
<body>
<h1> My First Heading From the Page of html </h1>
<img src="./images/download.jpg">
<img src="./images/lenovo.jpg">
</body>
</html>

Look at size of your lenovo.jpg image it have very high resolution please use low resolution or define width and height in img tag.

If you don't have a strict requirement not to use express, I suggest you to use express, and you can handle it with express' static file handling method:
https://expressjs.com/en/starter/static-files.html

Related

Read static files with express got "Cannot Get /"

I tried to learn how to read static files with express from a reliable website. And then I found that not know why, my terminal tell me I'm success but website show me "Cannot Get /"(as following image show). I had found a lot of solution (e.g. in my html file, I add script src to socket.io) but still fail. Where can I start to deal with it? Please help me...
terminal show success
website show error
And the following is my code:
C:\...\1-on-1-webrtc\server.js
const express = require('express')
const app = express()
const http = require('http').createServer(app)
// static data
app.use('/', express.static(__dirname + '/public/'))
// TODO: Signaling
//start server listen 8080 port
http.listen(8080, () => {
console.log(`Server running in 8080`)
})
C:\...\1-on-1-webrtc\pubilc\index.html
(origin)
"hello"
(after)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>111</title>
<script src="https://cdn.socket.io/socket.io-3.0.5.js"></script>
</head>
<body>
<h1>"hello"</h1>
<script>
var socket = io();
</script>
</body>
</html>
I change Your code a little and here is my solution:
Firstly change your name of public folder to correct. Not "pubilc" only "public".
Folder & File Structure:
server.js :
const express = require("express");
const app = express();
const port = 8080;
// const http = require("http").createServer(app);
// static data
app.use("/", express.static(__dirname + "/public"));
//start server listen 8080 port
app.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`);
});
index.html (without any changes) :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>111</title>
<script src="https://cdn.socket.io/socket.io-3.0.5.js"></script>
</head>
<body>
<h1>"hello"</h1>
<script>
var socket = io();
</script>
</body>
</html>
Output :
Tested with: express 4.17.2 node 16.13.0 Linux Ubuntu 20.04 and Win10

How to create and download file from angular app? Issue with blob

I can't download my generated file from app. Code now looks like this:
async handleFileTranslateAction(): Promise<void> {
this.progressSpinerIsVisible = true
this.originLanguageSelect = await this.languageService.getById(this.selectedOriginLanguage).toPromise()
this.destinationLanguageSelect = await this.languageService.getById(this.selectedDestinationLanguage).toPromise()
const result = await this.translateService.getTranslatedJson(
this.fileInput.getFile(),
this.originLanguageSelect,
this.destinationLanguageSelect
)
const result2 = JSON.stringify(result)
console.log(result2)
const blob = new Blob([result2], { type: 'text/json' });
console.log(blob)
this.fileDownloadUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
// const blob = new Blob([result2], { type: 'text/json' });
// const url= window.URL.createObjectURL(blob);
// window.open(url);
const element: HTMLElement = document.getElementById('download-final-json-button') as HTMLElement;
element.click()
this.progressSpinerIsVisible = false
}
When i consol loging result2, everything showing up correctly, all data is fine, but when i try console log blob and even, when i download a file, i always recieving file contains only this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>TachoTranslations</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght#300;400;500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body class="mat-typography">
<tt-root></tt-root>
<script src="runtime.js" defer></script><script src="polyfills.js" defer></script><script src="styles.js" defer></script><script src="vendor.js" defer></script><script src="main.js" defer></script></body>
</html>
The commented section don't works for me. I just want to download json file.
you can try with
blob = new Blob([response], { type: 'text/json' });
const url = window.URL.createObjectURL(blob);
window.open(url);
edit.
something like this?
downloadFromLocal(path) {
let link = document.createElement('a');
link.setAttribute('type', 'hidden');
link.href = `${path}`; //path to the file
link.download = 'autocertificazione.docx';// name that the file takes
document.body.appendChild(link);
link.click();
link.remove();
}

How do I load extension when viewing local file

I am using the example taken from viewer-javascsript-offline.sample
I have an extension that was created using nodejs tutorial (link) that I got it working using the tutorial code to register the extension. However, when I tried the same thing using the offline viewer code sample (using viewer3D instead of viewingApplication), I am not able to view the extension's button.
note: I can guarantee that the handleselectionextension.js is working fine as I've got it working in the tutorial version.
codes:
index.css and index.html
.handleSelectionToolbarButton {
background-image: url(https://github.com/encharm/Font-Awesome-SVG-PNG/raw/master/white/png/24/object-group.png);
background-size: 24px;
background-repeat: no-repeat;
background-position: center;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Very Basic 3D Viewer</title>
<link rel="stylesheet" href="https://developer.api.autodesk.com/modelderivative/v2/viewers/style.min.css?v=4.2.*" type="text/css">
<link href="index.css" rel="stylesheet" />
</head>
<body>
<div id="MyViewerDiv"></div>
<!-- The Viewer JS -->
<script src="https://developer.api.autodesk.com/modelderivative/v2/viewers/three.min.js?v=4.2.*"></script>
<script src="https://developer.api.autodesk.com/modelderivative/v2/viewers/viewer3D.min.js?v=4.2.*"></script>
<script src="handleselectionextension.js"></script>
<!-- Developer JS -->
<script>
var myViewerDiv = document.getElementById('MyViewerDiv');
var viewer = new Autodesk.Viewing.Private.GuiViewer3D(myViewerDiv);
var options = {
'env': 'Local',
'document': "0/1/Design.svf",
'extensions': ["HandleSelectionExtension"]
};
Autodesk.Viewing.Initializer(options, function() {
viewer.start(options.document, options);
});
</script>
</body>
</html>
The extension config is not for Initializer, you have to pass it to 2nd argument of the viewer constructor like this:
var config3d = {
'extensions': ["HandleSelectionExtension"]
};
var myViewerDiv = document.getElementById('MyViewerDiv');
var viewer = new Autodesk.Viewing.Private.GuiViewer3D(myViewerDiv, config3d);
var options = {
'env': 'Local',
'document': "0/1/Design.svf"
};
Autodesk.Viewing.Initializer(options, function() {
viewer.start(options.document, options);
});

I receive a GET error when trying to serve html page with image using Node.js

I am new to Node.js and am unable to find a way to solve my issue. I have written a server using Node.js to serve a html webpage. The problem is that it wont display the images that are in the same folder. I am trying to serve my webpage as well as my images and css file. Any help would be appreciated.
Relevant code:
server:
var http = require('http');
var fs = require('fs');
const PORT = 8080;
function handleRequest(request, response) {
console.log(request.url);
var bool = 0;
var index = fs.readFileSync("index.html", {
encoding: "utf-8"
});
if(request.url == "/")
{
bool = 1;
response.end(index);
}
else if(request.url == "/index" || request.url == "/index.html")
{
bool = 1;
response.end(index);
}
else if(bool == 0)
{
response.statusCode = 404;
response.end("Not Found");
}
}
var server = http.createServer(handleRequest);
server.listen(PORT, function() {
console.log("Started server on http://localhost:%s", PORT)
});
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Personal Webpage</title>
<link rel="stylesheet" href="index-css.css"/>
</head>
<body>
<h1>Welcome!</h1>
<p>My paragraph.</p>
<img src="/family.jpg" alt="Family" style="width:342px;height:513px;">
<img src="/Another.jpeg" alt="Another" style="width:500px;height:500px;">
</body>
</html>
I recommend use app.use(express.static(__dirname + '/FOLDER_NAME')) in order to expose a folder to serve static files to the client. Here is the documents about serving static files using express.
Edit: Here is a simple working example of serving a index.html using express
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});

NodeJS and Express : CSS not loading

I have created my own server and router files to serve my html pages. The page renders, but my problem is, it renders without css styling.
I'm using express.static to serve my /public files, which in theory should serve the css file - or so I thought. I have done a Google search of my problem and looked at the links on the first couple of pages but I still cannot fix my problem. Can anyone sport my mistake?
My directory is:
NODEJS
node_modules
public
css
style.css
js
router
main.js
views
my html files
My server code is:
var express = require('express');
var app = express();
var fs = require('fs');
var url = require('url');
var path = require('path');
var http = require('http');
var router = express.Router();
var bodyParser = require('body-parser');
app.use(bodyParser());
app.use(express.static(__dirname + "/public", {maxAge: 3456700000}));
require('./router/main')(app);
app.engine('html', require('ejs').renderFile);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port);
});
My Router code is:
var url = require('url');
module.exports = function (app) {
app.get('/', function (req, res) {
res.render('../views/default.html');
console.log("Home page displayed");
});
// Some more get requests for different pages
};
My html code is:
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>Index</title>
<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/css/style.css">
</head>
[error fixed: code needed re-arranging and chrome browser needed updating to most recent version]
the css path looks wrong it should be /css/style.css instead of portalstyle.css, like this
<link rel="stylesheet" type="text/css" href="/css/style.css">