I'm trying to send different html files to users, with index.html being a bunch of hyperlinks that a user can click on to see that file, but I get an error that says "cannot GET (that file's name)" whenever I click on a hyperlink.
var app = require('express')();
var http = require('http').createServer(app);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Here's my index.html:
<html>
Pong Game
</html>
You can define a public static file folder like this:
app.use(express.static(__dirname + '/public'));
Everything you have in your public folder will be accessible at the root of your URL (i.e. /pongClient.html)
Basically you have to setup the node server so that it knows where to get the file from and You can setup a static server in this case. The syntax in express can be found here
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
var app = require('express')();
var http = require('http').createServer(app);
app.use(express.static(__dirname)) //since the index.html and probably pongClient.html are in the current directory based on your code.
http.listen(3000, function(){
console.log('listening on *:3000');
});
Nodejs has nothing to do with hyperlink. But if you want your user to access different page use
app.get('/', function(req, res){
res.send('<p>Pong Game</p>\n');
});
The port number is 80(I am assuming your web server port is 80).Mainly you have to give full URL(accessible ones).
Related
I'm using Nodejs and Express to create a dynamic webpage.
I have a home.ejs file that has this iframe:
<iframe id="newstable" src="/news_tables/2018-08-04.html" height="1000" width="100%"></iframe>
My folder directory is:
News_Aggregator (includes app.js)
News_Aggregator/news_tables (includes a bunch of html files, e.g. `2018-08-04.html`)
News_Aggregator/views (includes my `home.ejs` file)
And my app.js:
const express = require('express');
const app = express();
app.set("view engine", "ejs");
app.get('/', function(req, res){
res.render('home.ejs');
});
app.listen(8000, () => {
console.log('Example app listening on port 8000!')
});
However, when home.ejs is rendered, my iframe doesn't load the html page:
This works in "normal" HTML. What am I missing to get the .ejs file to find this and render correctly?
You get the error because the server dosen't know where to get the files from.
First You must define where the static .ejs files will be. Lets say something like this. if your files are in a public folder(ejs,css etc) and you will get them from there. Setup both with:
app.use(express.static(__dirname + '/public'))
app.set('views', path.join(__dirname, '/public'));
from here you can just in your response if you have a home.ejs file
res.render('home', {});
You should look over Express static() from here and learn how to serve files
The fact your HTML is generated from a .ejs file is irrelevant.
Your HTML says the browser should ask the server for the URL /news_tables/2018-08-04.html.
Your HTTP server has a route app.get('/', and no other routes.
Your HTTP server doesn't know about the URL /news_tables/2018-08-04.html, so it returns a 404 Not Found.
You need to write code which will serve up all the URLs you want it to.
You should probably look at the Express static() middleware if you want to serve static files.
The only thing that works is removing ".html" from address "localhost:3000/index.html".
I am currently working on a project which uses socket.io with NodeJS to control something else. This is my code so far:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var contents = fs.readFileSync("data.json");
var remoteLayout = JSON.parse(contents);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/edit', function(req, res) {
res.sendFile(__dirname + '/edit.html');
});
app.use(express.static(__dirname));
io.on('connection', function(socket) {
console.log('a user connected');
socket.on('disconnect', function() {
console.log('user disconnected');
});
});
http.listen(8080, function() {
console.log('listening on *:8080');
});
It is my code shortened to the parts which are relevant.
So my question is, when I run this code in node, and I open the page [myIPAddress]:8080 it opens up index.html like it should and at the top of Chrome, it says [myIPAddress]:8080. Now if I to the bar which shows the page's URL at the top, and change that to [myIPAddress]:8080/handler.js it opens a page with my js script printed out on it. How do I make it so that the person cannot go to that [myIPAddress]:8080/handler.js page?
I'm not sure if it matters, but the folder with the main.js file has also index.html, edit.html, and handler.js.
The problem is this:
app.use(express.static(__dirname));
When you do that, you've exposed all files in the __dirname directory for anyone to see including your server files that are located in that directory. Instead, you should move your static files that you intend for the public to have access to to some other directory and then use:
app.use(express.static(someOtherPath));
This will keep your server files in __dirname private and expose only the files you intend to be public that you have located in someOtherPath.
If handler.js is actually intended for use in your web pages and thus must be made available to the browser, then you cannot prevent anyone from looking at it. If your webpage needs to use it, then the browser must be able to download it and if the browser must be able to download it, then you cannot prevent a person from seeing it. You can do all sorts of things like obscure it to make it less intelligible to a person, but to any determined hacker, the logic will still all be there and you can't hide any Javascript intended to run in a browser.
Logic that you want to protect MUST be only on your server, perhaps usable via Ajax calls. You can't keep code secret that must run in a browser.
I have a node server file, app.js which uses express.
The file looks like this
var express = require('express')
var app = express();
app.use(express.static(__dirname + '/public'))
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
If I run $ node app.js from my terminal it launches and if I navigate to localhost:3000 on my machine I see Hello World!.
I have uploaded the file to a server and try and navigate to the index.html file , which is in the public folder, however it doesn't work.
Maybe I am missing many steps, but can anyone advise how I can launch the node app on my server?
Your server doesn't send index.html anywhere. It only serves "/" path by sending text "Hello World!".
With Node.js, you have to tell which content you want to send for each route.
You can simply send the specific file : (sure, but dirty)
app.get('/index.html', function (req, res) {
res.send(PATH_TO_FILE/index.html);
});
Or specify which path to use to serve files by default :
app.use(express.static(__dirname + '/public'));
And you put all your public files to serve automatically in the public folder :
YOUR_PROJECT/public/AUTOMATICALLY_SERVED_FILES
Where AUTOMATICALLY_SERVED_FILES can be index.html or css/style.css for exemple.
NB : NGINX is not useful at this point.
On the server, nodejs is configured right?
I use forever with nodejs, it is useful if you would like to use nodejs like a service on linux base system.
I'm trying to build a simple chat app using node and socket.io. I am following the tutorial listed here: http://socket.io/get-started/chat/
My issues is that the tutorial has some javascript that is placed in a script tag directly in the html. I would like to move this code into it's own js file.
I made a file called chat.js, that is in the same directory as my index.html and index.js. In my html I put the following code in the header (I also tried right before the ending body tag too)
<script type="text/javascript" src="chat.js"></script>
However, when I run node index.js in terminal and go to localhost, I get a 400 for chat.js. I've tried placing "/chat.js" as well as "./chat.js" with no luck. All three files are in the same directory.
Any clues to what I am doing wrong will be appreciated.
My index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
node.js does not automatically serve any files like other web servers do. If you want it to send chat.js when the browser requests it, you will have to create a route for it in your node.js code so that the web server will send it.
If you use something like the Express framework, this can be done in perhaps one line of code with app.use(express.static(...)).
Notice how in the demo you linked to, there's a specific route for the / path. You need a similar route for /chat.js or you could use app.use(express.static(...)) to configure the automatic serving of a whole directory of files.
In the future, if you show your actual server code, then we could help more specifically with actual code that fits into your server.
Now that you've shown your code, you could add a specific route for /chat.js:
app.get('/chat.js', function(req, res){
res.sendFile(__dirname + '/chat.js');
});
Or, if you move chat.js to be in a public sub-directory under your app code, then you could serve all files in that directory automatically with this:
app.use(express.static('public'));
When Express gets a request for a route that doesn't have a specific handler, it will check the public sub-directory to see if a file matches the request name. If so, it will automatically serve that file.
I have the following code:
var express = require('express');
var app = express();
var server = require('http').Server(app);
app.get('/', function(req,res){
res.sendfile(__dirname + '/index.html');
});
server.listen(3000);
However, only my index.html page displays, and I have a GET error for my other files. When I load index.html at localhost:3000, I have errors in the console with trying to find my main.js and app.css files. Even when I include my other files as a src in the html file, they are not able to load. I think this may be because I am only sending the single html file to the server. How can I handle this so that all of the relevant files are sent to the server?
Using
res.sendfile(__dirname + '/index.html');
in response to a get request won't serve up all your static files, only the individual index.html file — meaning your css and javascript files will not be found by your server (even when you link to them in your html).
You need to use the included express static middleware (the only included middleware in express v4).
If your static files are in the same directory as your server.js file then add
app.use(express.static('.'));
This serves up all of your local static files and makes them accessible on your server.
I wrote a blog post on this a while back:
https://medium.com/#willsentance/how-to-avoid-main-js-style-css-not-found-or-how-i-learned-to-love-serving-static-files-with-node-2121255da0fd
You haven't offered a route to the linked files.
Use the static middle-ware: http://expressjs.com/api.html#express.static
From the docs:
Following are some examples of using the express.static middleware in an Express app.
Serve static content for the app from the "public" directory in the application directory.
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static".
// GET /static/style.css etc.
app.use('/static', express.static(__dirname + '/public'));
Disable logging for static content requests by loading the logger middleware after the static middleware.
app.use(express.static(__dirname + '/public'));
app.use(logger());
Serve static files from multiple directories, but give precedence to "./public" over the others.
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/files'));
app.use(express.static(__dirname + '/uploads'));