i created a javascprit file to listen to http port 3000 and send a html file which plays a video file
var http = require('http')
var url = require('url')
var express = require('express')
var app = express()
const fs = require("fs")
const path = require('path')
app.get("/", function(req, res){
res.setHeader("Content-Type","text/html")
res.sendFile(__dirname + "/index.html")
res.sendFile(__dirname + "/vid_1.html")
}
)
app.listen(3000, function(){
console.log("listening on port 3000")
console.log(__dirname)
})
the hmtl file
<!DOCTYPE html>
<html lang="en">
<body>
<video controls>
<source src="vid_1.mp4" type="video/mp4" />
<p>
Your browser doesn't support HTML video. Here is a
link to the video instead.
</p>
</video>
</body>
</html>
when i call the http://localhost:3000 the video player starts but no video is played but when i directly run my index.html the video plays can someone please help me
i tried sending the video file directly as a response without the html file which worked but i need to use a html file for the project i am bulding
You can only send one file with res.sendFile(). You should serve the vid_1.mp4 route similar to the html page like this:
app.get("/vid_1.mp4", (req, res) => {
res.sendFile(__dirname + "/vid_1.mp4")
})
You could also have a public folder to serve many more files like this. You can find more about this here: https://expressjs.com/en/starter/static-files.html
Related
I stripped down the problem to the bare minimum, here's the situation:
The most basic index.html possible, with no DOM elements and only one script, located in the same folder:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script src="script.js"></script>
</body>
</html>
The simplest possible script.js, which is just a console.log statement:
console.log("%cI'm working!", "font: bold 17px arial; color: #3e9;");
a very simple server.js:
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
const PORT = 3000;
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
}).listen(PORT);
console.log(`Listening on port ${PORT}`);
If I run the page locally, i.e. by launching index.html with my web browser, everything works fine, and I see the log in the console. If, instead, I try to launch the server using node server.js, I come across a very weird error in which script.js appears to contain the contents of index.html, resulting in a syntax error.
Here's a screenshot of DevTools for clarity:
What causes this? How can I correctly include the script on my local server?
Your server responses all requests with index.html. You need a routing.
The most basic approach is
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
var script = fs.readFileSync('script.js');
const PORT = 3000;
http.createServer(function (req, res) {
if (req.path.endsWith('script.js')) {
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.end(script);
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
}
}).listen(PORT);
console.log(`Listening on port ${PORT}`);
This should be only the first step to understand the basics. Usually you would use a framework like Express with a routing as described in https://expressjs.com/en/guide/routing.html and serve static files as described in https://expressjs.com/en/starter/static-files.html
An example with Express:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.static(__dirname));
But this will serve all files in your project root. You should restructure your project and move the files for your website into a separate folder, e.g. public:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.static(path.join(__dirname, 'public')));
Let's say i have a simple project, index.html and one .js file with a method:
<!DOCTYPE html>
<html lang="pl">
<HEAD>
<script src="controller.js"></script>
<meta charset="utf-8"/>
<title>Project</title>
</HEAD>
<body>
<textarea id ="someID" name = "textFieldName"></textarea>
<button onclick="showNewData()">Button</button>
<p id="score"></p>
</body>
</html>
function getText(){
value = document.getElementById('someID').value;
}
function showNewData(){
getText();
document.getElementById('score').innerHTML = "Current data: "+value;
}
I tried to do the same on localhost:3000. So i've done npm project with express and hbs dependencies. It start from server.js file:
const express = require('express');
const port = 3000;
const app = express();
app.set('view engine', 'hbs');
app.get('/', (req, res) => {
res.render('index')
})
app.listen(port);
In "views" folder i have hbs file looked the same like former index.html file but it can't use javascript method from external file. Does anyone know how to do that?
in hbs file
As far as the browser knows, it is HTML. Clients do not care, and cannot know, if an HTTP response is generated by reading a static file or dynamically with some form of server side processing.
src="controller.js"
The value of the src attribute has to resolve to a URL containing the JavaScript
app.get('/', (req, res) => {
res.render('index')
})
The only URL your web server knows about (and so will provide anything other than a 404 error for) is /.
If you want /controller.js to provide a JS file then you need to write code to make that happen.
How to handle static files is covered in the Express Getting Started Guide.
That's my first-day learning Node.js and on making a basic server that basically renders 1 page containing a header tag, I get an error saying that the CSS file can't be loaded
That's my code:
const express = require('express');
const path = require('path');
const HOST = '127.0.0.1';
const PORT = 3000;
const app = express();
//app.use("/public", express.static(path.join(__dirname, "static")));
app.get('/', (request, response) => {
response.setHeader("Content-Type", "text/html");
response.sendFile(path.join(__dirname, "static", 'index.html'));
});
app.listen(PORT, HOST, () => {
console.log(`Running Server on ${HOST}:${PORT}`)
});
The HTML file:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Hello World!</title>
<link rel="stylesheet" type="text/css" href="./css/index.css">
</head>
<body>
<h1>Hello World From Node.js!</h1>
</body>
</html>
The Error:
File Tree:
I just want to be pointed at the missing part here for the css file to be linked with the HTML
Note: the CSS file is loaded when I directly run the HTML by browser
You can use express.static() (that you commented out) to serve static files.
According to docs you need
app.use(express.static(path.join(__dirname, "static")));
This way CSS should load. Any request like http://127.0.0.1:3000/css/index.css will be checked against static directory and if matching file is found Express will serve it.
If request does not match the file in that directory (for example http://127.0.0.1:3000/) Express will continue to look for other matching routes and will execute app.get('/', fn) because it'll match.
For reference, full code:
const express = require('express');
const path = require('path');
const HOST = '127.0.0.1';
const PORT = 3000;
const app = express();
app.use(express.static(path.join(__dirname, "static")));
app.get('/', (request, response) => {
response.setHeader("Content-Type", "text/html");
response.sendFile(path.join(__dirname, "static", 'index.html'));
});
app.listen(PORT, HOST, () => {
console.log(`Running Server on ${HOST}:${PORT}`)
});
UPDATED There are two ways to use express.static() as docs explain:
When calling app.use(express.static(path.join(__dirname, "static"))); (without a prefix specified) index.css file, for example, will be available at
http://127.0.0.1:3000/css/index.css
When calling app.use("/public", express.static(path.join(__dirname, "static"))); (with /public prefix) the same index.css file will be available under /public prefix at
http://127.0.0.1:3000/public/css/index.css
This approach counter-intuitive because index.html needs to be updated to load CSS from this prefix (and will only work when loaded via http://127.0.0.1:3000/, not when opened as a local file):
<link rel="stylesheet" type="text/css" href="./public/css/index.css">
you can load the static assets by creating a virtual path like
app.use('/assets',express.static(__dirname + '/public/css'));
where the public is the directory where all your assets are stored,in which CSS is the folder where is all your CSS file are stored , you can you the virtual path in the link tag , href attribute for loading the css ,eg: if you have template file ,you write in it ,the link tag i have tried with the same directory structure like yours and tried to emulate the bug and fixed the css load issue you can refer : https://github.com/ardnahcivar/Node.js-Code-/tree/master/11-17-18 the code
I'm trying to write simplest possible server that serves html page with client side scripts.
Already tried based on http://expressjs.com/en/starter/static-files.html,
Using express.js to serve html file along with scripts, css, and images and
How to load JS file in html using express server, but still I don't get it.
File structure I'm using:
node_modules
resources
resources/page.html
resources/script.js
index.js
package.json
index.js:
const express = require('express');
const app = express();
const port = 3000;
const path = require('path');
app.use(express.static(__dirname + '/resources'));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname , 'resources', 'page.html'));
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
page.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body>
Content
</body>
<script scr="script.js"></script>
</html>
script.js:
var i = 0;
setInterval(() => {
if (i < 10) {
console.log(i);
i++;
}
}, 100);
I type in google chrome browser address localhost:3000/ and page is successfully loader ("Content" string is displayed), but script script.js is not running (empty console). I expect browser to retrieve script.js file and print numbers to console when page.html is loaded.
In the page.html file, change the property scr to src in the script tag and it will work.
So I have some code (app.js, in the server)
console.log("Server started. If you're reading this then your computer is still alive."); //Unnecessary test command to make sure everything works.
var express = require("express");
var app = express();
var serv = require("http").Server(app);
app.get("/", function(req, res) {
res.sendFile(__dirname + "/client");
});
app.use("/client", express.static(__dirname + "/client"));
serv.listen(2000);
//Set up server stuff. This isn't touched.
var io = require("socket.io")(serv, {});
io.sockets.on("connection", function(socket) {
console.log("Socket connection"); //This will print to the server, not the developer console in your browser.
});
//Initialize sockets and set up socket listeners. This isn't touched either, except when adding new events.
And some more code:
<!DOCTYPE html>
<html>
<head>
<title>Multiplayer!</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
var socket = io();
</script>
</body>
</html>
My folder structure is:
multiplayer_game
app.js
package.json
node_modules (folder)
node stuff
client (folder)
index.html
js (folder)
img (folder)
server (folder)
Where the farther in the file is, the more "nested" it is.
When I open the page by doing node app.js (folder already cd'ed) and go to localhost:2000, I get "Cannot GET /". When I go to localhost:2000/client, I get everything fine. What can I do to fix my code?
You will need a router for that.
const router = express.Router;
router.get('/', function(req, res) {
res.sendFile(__dirname + "/client");
});
app.use('/', router);
A middleware is not capable to handle various http methods.