Read static files with express got "Cannot Get /" - html

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

Related

Send data from SerialPort to socket.io

I'm struggling with socket.io, express, and node.js.
I send data from an Arduino to my cmd. This is done with the serialport libary. But now I want this data displayed on my web browser. I'm using the express library for this. I have index.js here is the connection with the arduino and browser. And an index.html
This code do I have:
code from index.js (node.js server):
var express = require('express'),
app = express(),
server = require('http').Server(app),
io = require('socket.io')(server),
port = 8888;
//Server start
server.listen(port, () => console.log('on port' + port))
//user server
app.use(express.static(__dirname + '/public'));
io.on('connection', onConnection);
var connectedSocket = null;
function onConnection(socket){
connectedSocket = socket;
}
//Arduino to CMD
const SerialPort = require('serialport');
const Readline = SerialPort.parsers.Readline;
const usbport = new SerialPort('COM4');
const parser = usbport.pipe(new Readline());
parser.on('data', console.log);
The data what is recieved from the serialport (Arduino), had to be displayed in the index.html (webbrowser). I tried already something but it doesn't work. It has to be printed in the <p></p> in the html code.
The index.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="text">
<p></p>
</div>
<script>
var text = document.getElementById('text');
var socket = io.connect('http://localhost:8888');
socket.on('data', function(message) {
text.innerHTML = message.data;
});
</script>
</body>
</html>
Instead of
parser.on('data', console.log);
Try this:
parser.on('data', function (data) {
io.emit('data', { data: data });
});
That should send the parsed data from the SerialPort to the socket, which should end up on the client side on the website.

Cannot get on http://localhost:3000/

I am using gulp.The tasks are getting run creating required folders. But I get Cannot GET/ error when run in browser.I have attached the image of my project structure and also the output in command line. .My index.html contains the following
<!DOCTYPE html>
<html lang="en" ng-app="helloWorldApp">
<head>
<title>Angular hello world app</title>
<link href="css/main.css" rel="stylesheet">
</head>
<body>
<ng-view class="view"></ng-view>
</body>
<script src="js/scripts.js"></script>
</html>
I want to know why it cannot get or not routed properly and what should be done. So the problem is when the server is running on localhost and I hit localhost:3000/ in browser it says cannot get with a white background.Following is my gulpfile.js
const gulp = require('gulp');
const concat = require('gulp-concat');
const browserSync = require('browser-sync').create();
const scripts = require('./scripts');
const styles = require('./styles');
var devMode = false;
gulp.task('css',function(){
gulp.src(styles)
.pipe(concat('main.css'))
.pipe(gulp.dest('./dist/css'))
.pipe(browserSync.reload({
stream : true
}))
});
gulp.task('js',function(){
gulp.src(scripts)
.pipe(concat('scripts.js'))
.pipe(gulp.dest('./dist/js'))
.pipe(browserSync.reload({
stream : true
}))
});
gulp.task('html',function(){
gulp.src('./templates/**/*.html')
.pipe(gulp.dest('./dist/html'))
.pipe(browserSync.reload({
stream : true
}))
});
gulp.task('build',function(){
gulp.start(['css','js','html']);
console.log("finshed build");
});
gulp.task('browser-sync',function(){
browserSync.init(null,{
open : false,
server : {
baseDir : 'dist'
}
});
console.log("finshed browser ");
});
gulp.task('start',function(){
devMode = true;
gulp.start(['build','browser-sync']);
gulp.watch(['./css/**/*.css'],['css']);
gulp.watch(['./js/**/*.js'],['js']);
gulp.watch(['./templates/**/*.html'],['html']);
});
Since your baseDir is 'dist' you need to run http://localhost:3000/html in the browser I think that should work.
You need to point browserSync to the dist/html/index.html file as the start page with index.
gulp.task('browser-sync',function(){
browserSync.init(null,{
open : false,
server : {
baseDir : 'dist',
index : "html/index.html"
}
});
console.log("finshed browser ");
});

Executable run from electron project isn't loading resources

I am making a electron application that launches an executable stored on my computer when run. If I run the exe by itself, it works correctly and loads all of the fonts. However, when run by the electron app, it opens, but non of the font files can be loaded. The exe is a compiled release project made in visual studio.
I tried putting the res folder into the same directory as index.html to no avail.
Code for index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<script>
var child = require('child_process').execFile;
var exePath = "C:\\Users\\name\\Documents\\Visual Studio 2015\\Projects\\Ten\\Release\\Ten.exe";
var parameters = ["test"];
child(exePath, parameters, function(err, data){
console.log(err);
console.log(data.toString());
})
</script>
</body>
</html>
Code for main.js
const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
win.webContents.openDevTools()
// Emitted when the window is closed.
win.on('closed', () => {
win = null
})
}
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (win === null) {
createWindow()
}
})
Thanks!
Does your exe use a relative path to load the fonts? If so, either change the exe to be more flexible, or in your call to execFile() specify the optional 3rd arg to specify the desired working directory.
var child = require('child_process').execFile;
var exePath = "C:\\Users\\name\\Documents\\Visual Studio 2015\\Projects\\Ten\\Release";
var exe = exePath + "\\Ten.exe";
var parameters = ["test"];
var options = {cwd:exePath};
child(exePath, parameters, options, function(err, data){
console.log(err);
console.log(data.toString());
});
If that doesn't work, my guess would be some kind of permissions problem. Is your electron app running as a different user to when you test the exe?

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