I'm trying to make a simple game using Node.js and HTML. I want to be able to run the game locally (so localhost). But when I start my Node server, only the HTML content is rendered - my images don't show up and the JS is not loaded. I reference JavaScript files, CSS files and images in the HTML code. Not sure why the server cannot reference these from within the HTML.
Here is my server code:
const path = require('path')
const http = require('http')
var fs = require('fs')
//Set port number:
const port = 3000
const requestHandler = (request, response) => {
console.log(request.url)
response.writeHead(200, {"Content-Type": "text/html"});
response.end(fs.readFileSync('game.html'));
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('Error: ', err);
}
console.log(`Game started\nGo to http://localhost:3000 to play\n`);
console.log(`Server is listening on ${port}...`);
})
Can anyone tell me how I can get my images/JS loaded?
TIA
You are not serving the static content correctly (i.e. images, CSS). Consider what happens when one navigates to http://localhost:3000/some_image.png - they will be served game.html!
You need to account for users requesting that content in your requestHandler by for example reading the file they want with fs.readFileSync(request.url). Remember to check that they can only request files you want them to be able to read!
You need static handlers to return static content. Check this
https://www.pabbly.com/tutorials/node-js-http-module-serving-static-files-html-css-images/.
Also, if your application is going to be huge then use some middle-ware like Express. (https://expressjs.com/)
If you use express framework, you can use static rendering:
app.use(express.static('public'));
where 'public' is the folder name
Related
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.
I want to enter path to the folder in browser and display all file names which located inside, i found that it will possible with node fs, but i also have code which runs at browser, and it need vars, located in file, which will run outside of the browser with node. I need to create server with node and runs all code from it? Or what you can reccomend me to reach this goal? PS: By the way i use webpack
There are differences between javascript in browser end and server end. You can't access the directory directly from the browser. You need some sort of backend technology like PHP, Java, node, python, etc in order to get the file list. You can use node server and below code for the reading directory. Then make a simple HTTP request to your backend server from the frontend.
const path = require('path');
const express = require('express');
const fs = require('fs');
const PORT = 3000;
const app = express();
app.get('/getfiles', async (req, res) => {
const directoryPath = path.join(__dirname, 'Documents');
let data = [];
await fs.readdir(directoryPath, function (err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
//listing all files using forEach
files.forEach(function (file) {
// Do whatever you want to do with the file
data.push(file)
});
});
res.send(data);
});
app.listen(PORT, ()=>{
console.log(`server running on port ${PORT}`);
});
I have a very simple https Nodejs server that serves an index.html that includes a request for a Javascript file. I cannot seem to get the browser to recognize the Javascript file.
<html>
<head>
<script src="deviceMotion.js"></script>
</head>
<body>
</body>
</html>
For this example, the contents of deviceMotion.js are immaterial. When I load the page and check Crhome debug tools, I receive a syntax error in the first line of the Javascript file, saying
Uncaught SyntaxError: Unexpected token '<'
I look at the "javascript" file's contents only to see that it is exactly the same as my index.html. This leads me to believe that there is an issue with the way my Node HTTPS server is serving the Javascript. Likely, it is just serving the html twice, even though my console logs show 3 separate requests being made, and only 2 when I remove the script tag from index.html. Obviously, it is trying to request the Javascript file, but there is something not right.
Here is the code for my server app.js
const http = require('http');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
console.log("request received");
console.log(req.headers.referer);
fs.readFile('./src/index.html', function (error, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
});
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
My files are structured such that I have app.js in the same directory as a folder called "src" and I have index.html and deviceMotion.js under src.
How can I control what files I serve and when depending on incoming requests? How can I differentiate requests made in order to serve the right file? I have tried parsing req.baseUrl and req.path and both are undefined.
Your Node.js server always returns a HTML file and sets the content type to HTML, so when your website requests the JavaScript file, it returns a HTML file, causing the Uncaught SyntaxError: Unexpected token '<' error. To fix the error, don't set the content type and let the browser figure it out, and also modify the code to return the requested file.
I have written some possible code below. However, it will need to be modified to suit your file structure.
const server = http.createServer((req, res) => {
console.log("request received");
console.log(req.headers.referer);
fs.readFile('./' + req.url, function (error, data) {
res.end(data);
});
});
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
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..?