Raspberry Pi Host a html page - javascript

I am using Raspberry Pi 3 with Windows IoT 10.I want to open a html webpage in the web browser.Here raspberry pi as web server,it has to display html page. I have tried in node js,but i am unable to read the html file. Here is my
code
var http = require('http');
var fs = require('fs');
var path = require('path');
var filepath;
filepath = path.join(__dirname,'/assets/index.html');
console.log(filepath);
http.createServer(function (req, res) {
// console.log(filepath);
fs.readFile(filepath, function (err, data) {
if (error) return console.error("Error in finding the file");
res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Length': data.length });
res.write(data);
});
}).listen(1337);
I have create an index.html page under assets folder. Is this the correct way to host a web page or please please help me.

Related

Node JS/localhost server is not showing the image

I created localhost/server on node js, and my pictures/img tag doesn't work
<div class="text-center">
<img alt = "Bulb" src="pic_bulboff.gif" class="rounded" alt="bulboff">
</div>
but the problem is that they show up when I open them in a regular browser without the server
const http = require('http')
const fs = require('fs')
const port = 3000
const server = http.createServer(function(req, res){
res.writeHead(200, { 'Content-Type': 'text/html'})
fs.readFile('index.html', function(error, data) {
if(error) {
res.writeHead(404)
res.write('Error: File not Found')
} else {
res.write(data)
}
res.end();
})
})
above is the node server.
is there a problem that I can't really see?
Thanks!!!
By default a nodejs http server does not serve ANY files at all. You've created an http server that serves index.html for ALL incoming requests. So, a browser makes a request from your web server and you send it the HTML content from index.html.
Then, the browser parses that HTML and sees an <img> tag with a src attribute of "pic_bulboff.gif" so the browser then sends a request to your web server asking it for the content for /pick_bulboff.gif. But, you web server just responds to that request by sending index.html. That obviously doesn't work. You need your web server to know the difference between different path requests so it will server index.html when the browser is requesting /, but will serve that image when the browser is requesting /pick_bulboff.gif.
While most people will use a simple web framework that has the serving of static files as a built-in feature (like the Express framework), you can do it manually if you want:
const http = require('http');
const fs = require('fs');
const port = 3000;
function sendFile(fname, contentType) {
res.writeHead(200, { 'Content-Type': contentType});
fs.readFile(fname, function(error, data) {
if(error) {
res.writeHead(404);
res.write('Error: File not Found');
} else {
res.write(data);
}
res.end();
}
}
const server = http.createServer(function(req, res){
if (req.url === "/") {
sendFile('index.html', 'text/html');
} else if (req.url === '/pick_bulboff.gif') {
sendFile('pick_bulboff.gif', 'image/gif');
} else {
res.writeHead(404);
res.end('Error: Unsupported path');
}
});
server.listen(port);
In a more typical implementation, you would put all static files in one directory hierarchy that was separate from your code and you would use functionality similar to express.static() in the Express framework to serve any file in that static files directory that matches an incoming request so you don't have to create a custom route for every single static file you're using in your project.

Node only sends html content to the client instead of sending a whole Vue app

I created a new vue project with the CLI and want to deploy it. Based on this documentation
https://router.vuejs.org/guide/essentials/history-mode.html#html5-history-mode
I added the history mode to the router. After running npm run build I took the example code for a static native Node server
https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations
const http = require('http')
const fs = require('fs')
const httpPort = 3000
http.createServer((req, res) => {
fs.readFile('../base/index.html', 'utf-8', (err, content) => {
if (err) {
throw err;
}
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'
})
res.end(content)
})
}).listen(httpPort, () => {
console.log('Server listening on: http://localhost:%s', httpPort)
})
So when navigating to localhost:3000 the vue project seems to load correctly
but I have a blank page with two errors
When I click on those js files it shows me the content of the index.html file. Obviously js is not able to understand this html content. How can I fix that problem?
Server will not send the whole vue app at once.
Browser get html file from server, when you browse to that url.
Browser parse the html file.
Browser detects assets (js, images, css).
Browser request those files.
It request those file from server, but you haven't initialized server to find those files.
So, need to add static files.
https://expressjs.com/en/starter/static-files.html
You can take reference from here
as #Sukul answer before, you just need to server the static files because you have now only one handler to server all the request coming with the HTML file (the mount point document) and when its requesting the *.js app it's expecting the valid javascript syntax instead it finds HTML, and that what the error messages are on the network tab
const http = require('http')
const fs = require('fs')
const nStatic = require('node-static');
var fileServer = new nStatic.Server('./public');
const httpPort = 3000
const controllers = (req,res)=>{
if(req.url.includes(".")
return fileServer.serve(req, res);
else
fs.readFile('../base/index.html', 'utf-8', (err, content) => {
if (err) {
throw err;
}
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'
})
res.end(content)
})
}
}
http.createServer(controllers).listen(httpPort, () => {
console.log('Server listening on: http://localhost:%s', httpPort)
})
node-static ref
however, I highly recommend you trying to use express.js

read and print file contents with nodejs server?

hello I'm using docker and ansible to launch a container which will then launch a server.js file, which needs to display the contents of an index.html file located in the same directory. I have this skeleton outline code which works in displaying "Hello World" to the screen when I curl the ip address running this server.js file
var http = require('http');
http.createServer(function (request, response)
{
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8080);
console.log('Server started');
the console.log does not display on the screen, seemingly only response.end does that, with printing 'Hello World' to the screen, so I've been trying to read in the index.html file as a variable and have response.end display it but with no luck.
I tried doing this:
var http = require('http');
http.createServer(function (request, response)
{
response.writeHead(200, {'Content-Type': 'text/plain'});
var fs = require('fs');
var readStream = fs.createReadStream('index.html');
readStream.pipe(response);
//response.end('Hello World\n');
}).listen(8080);
console.log('Server started');
but when I tried to curl it it resulted in a an Error 52 empty reply from the server, am I not doing enough to read in my index.html file and store it as a string variable? thanks.
var http = require('http');
var fs = require("fs");
http.createServer(function(req, res) {
fs.readFile("index.html","utf8" ,function(err, contents){
console.log(contents);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(contents);
res.end();
});
}).listen(3000);
if you want to show the contents of the file on request to the server try this.

making js and other files available to html via node.js http server

I have a very simple web server like this:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile('./index.html', 'utf-8', function (err, content) {
if (err) {
res.end('something went wrong.');
return;
}
res.end(content);
});
}).listen(8080);
console.log("Server running on port 8080.")
This renders my index.html without any issues, but if I try to reference another file in my index.html via a script tag for instance, the site just gets stuck, unable to find the file which exists in the server directory.
How can I make those files available to my index.html file?
Please keep in mind that I realize this can be done much more easily with Express but I do not wish to use Express. I am trying to learn how things work behind the scene. Thanks in advance.
You need to make the directory visible to public. Its is recommend to use framework while developing the Node.js application.
Here is the code below to server file without framework.
var basePath = __dirname;
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function(req, res) {
var stream = fs.createReadStream(path.join(basePath, req.url));
stream.on('error', function() {
res.writeHead(404);
res.end();
});
stream.pipe(res);
}).listen(9999);
Refer : Node itself can serve static files without express or any other module..?

Node.js server gives problems with scripts and images

I just started using node js and I've moved one of my websites on it:
var http = require('http');
var fs = require('fs');
var app = http.createServer(function (req, res) {
fs.readFile('./index.html', 'utf-8', function(error, content) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.end(content);
});
});
app.listen(8080);
The index.html is my website home page. With only html it works, but if i put tags in it (for including jquery for example), it gives JS errors in firebug : Uncaught syntax error : unexpected token < in jquery.js, and then of course '$ is undefined'.
It doesn't load images either.
I don't really need to do some routing or use Express framework or anything, it's just a simple one-page website.
What am I doing wrong ?
Your server isn't handling requests for images or other resources. All requests are given the same response of the ./index.html page.
This means that if an external script or an image is included in the page, when a request is made by the browser for those resources, the original index.html page will be delivered instead.
NodeJS is fairly low-level. You need to set up your server to manually handle requests for different types of resources based on the URL for each request.
Your best bet will be to read through some NodeJS tutorials. They should cover the basics of serving content, though many of them won't deal with the lower-level details, and will suggest packages like Connect or Express.
Change your code to this, and you'll see all the resources being requested.
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
var app = http.createServer(function (req, res) {
var pathname = url.parse(req.url).pathname;
var ext = path.extname(pathname).toLowerCase();
console.log(pathname);
if (ext === ".html") {
fs.readFile('./index.html', 'utf-8', function(error, content) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.end(content);
});
}
});
app.listen(8080);

Categories