Node Server Not Loading CSS File - javascript

I'm making a chat application using a node server but when I start the node server and point my browser to localhost:3000 it loads the HTML document but not the CSS file which is supposed to load when the HTML document loads. How do you load the CSS file so that the HTML document uses it?
HTML document code
<html>
<head>
<title>Socket.IO Chat by Flow</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="chat.js"></script>
</head>
<link rel="stylesheet" type="text/css" href="css.css">
<body>
<table align="center" id="chat-box">
<td>
<ul id="messages"></ul>
<form action="">
<input type="text" placeholder="Press enter to send a message..." autocomplete="off" id="m">
</form>
</td>
</table>
</body>
JavaScript document code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = 3000;
app.get('/', function(req, res){
res.sendFile(__dirname + '/chat.html');
});
io.on('connection', function(socket){
});
http.listen(port, function(){
console.log('Listening on port: ' + port);
});

You haven't defined any routes that would provide the CSS file. The only route you've defined is
app.get('/', function(req, res){
res.sendFile(__dirname + '/chat.html');
});
...which will only ever serve chat.html.
To serve other files/resources, define other routes, perhaps a catch-all route that serves any matching file from a public directory.
For instance, this tutorial says you can serve any static files from the directory public by doing this:
app.use(express.static('public'));
More about routing in the routing tutorial. That whole series of tutorials may well be useful, in fact.

Related

Node js server doesn't show images in html file

I'm trying to use node js to show an image within an html file, but the image doesn't show up.
If I try to open the html file with a browser the image shows up without problem, but when I run it from the node js server it doesn't work.
Here is my node js code:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('pruebaFoto.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
Here is the html code:
<!DOCTYPE html>
<html>
<head>
<meta http-equi="refresh" content="1"> <!--I use this meta tag for refreshing the page each second-->
</head>
<body>
<h1>Image: </h1>
<img src="./image.jpg" alt="image">
</body>
</html>
The image and all the code are in the same path.
You need to create a router so the server can respond to different requests with different content.
There are many options for this, a popular option is to use a library like https://expressjs.com/

How to use external javascript file into an ejs file

I'm working in a new web portal. So far using the express and node.js i have a server and some ejs files.
The body structure of my site is like this:
- node modules
- public
--javascript
---myScript.js
-views
--pages
---index.ejs
---about.ejs
--partials
---footer.ejs
---head.ejs
---header.ejs
package.json
server.js
server.js
var express = require('express');
var app = express();
app.set('view engine', 'ejs'); // set the view engine to ejs
app.get('/', function(req, res) {res.render('pages/index');}); // index page
app.get('/about', function(req, res) { res.render('pages/about');}); // about page
app.listen(8080);
console.log('Portal is listening to port 8080 ');
and the index.ejs
<html lang="en">
<head>
<% include ../partials/head %>
</head>
<body class="container">
<header>
<% include ../partials/header %>
</header>
<main>
<div class="jumbotron">
<h1>MyPortal</h1>
<button>Press</button>
<% var test = 101; %>
</div>
</main>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
In the partials i want to call and use an external .js file /public/javascript/myScript.js so i can use variable from it in my ejs page or send a variable.
my js file have a simple function (just to see if it's working) that print in console if the button (in index.ejs) is pressed.
myScript.js
$(function() {
$("button").on("click", function () {
console.log("button pressed");
});
});
I'm trying to call the external js in head.ejs (or in index.ejs)...
<!-- views/partials/head.ejs -->
<meta charset="UTF-8">
<title>MyPortal</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style>body { padding-top:50px; } </style>
<script type="text/javascript" src="/pubic/javascript/myScript.js"></script>
but i'm getting this error (in console)
Loading failed for the <script> with source “http://localhost:8080/pubic/javascript/myScript.js”.
Any idea why this happens and how to solve it?
Since you are trying to load client-side JavaScript, the fact you are using EJS is irrelevent. A standard HTML script element is all you need in the template, and you have that.
You do, however, need to provide a URL (with the src attribute) that the web browser can use to fetch the script … and your script has no URL.
You are getting the message Loading failed for the with source “http://localhost:8080/pubic/javascript/myScript.js”. because it is a 404 Error.
You should use the static module to provide the JS file with a URL.
app.use("/public", express.static('public'))
Add this to your server.js file,
app.use(express.static(__dirname + "/public");
And to link the js file with your ejs file,

How to get elements from another HTML file

I'm trying to make a node.js application that takes the input from a text box in an HTML file. I want to store this value in an array, although I'm not sure how. My overall goal is to make a chat application and I assume there is some easier way to get the input without having to reference an HTML file.
Also, are there any templates for an html file because I'm not very skilled enough with HTML to make a decent-looking webpage. So if there is some template I could use, everything would look better.
My code:
var events = require('events');
var express = require('express');
var http = require('http');
var app = express();
var msg = [];
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
app.read('/', function() {
});
app.listen(3000, function() {
console.log("Server is running on port " + 3000);
});
#firstHead {
font-family: Georgia, 'Times New Roman', Times, serif;
}
<header>
<h1 id='firstHead'>
This is a header!
</h1>
</header>
<body>
<input type="text" id="inText" placeholder="Enter text here" />
</body>
Help appreciated!
First of all, your HTML code has so many mistakes. This the correct version of your code (You won't be using it, it's just to give you an idea of what mistakes you've done):
<!DOCTYPE html>
<html>
<head>
<style>
#firstHead {
font-family: Georgia, 'Times New Roman', Times, serif;
}
</style>
</head>
<body>
<h1 id='firstHead'>
This is a header!
</h1>
<form id="msg" method="GET" action="/msg">
<input type="text" name="msgContent" id="inText" placeholder="Enter text here" />
<input type="submit" value="Send">
</form>
</body>
</html>
Now this HTML page will send input contents to localhost:3000/msg as a POST request See here for more details, the problem here is that page will be refreshed or redirected (depending on your implementation, you should in this case use AJAX if you want SPA). Even if you used AJAX it will be hard for you to implement a chat application using HTTP requests. It would be a better idea to use WebSocket protocol to achieve this functionality. There's a module called Socket.io that will help you a lot. It has an event-driven system as it's great for real-time applications, you can check their official website; they've have an example of a chat application written in few hundred lines of code.
Now let's move to your server-side code, firstly .. there's no method of express called read, here's a working version of your code:
var express = require('express');
var http = require('http');
var app = express();
var msg = [];
app.get('/', function(req, res){
//You should use some template engines like EJS or Pug to render your HTML page with messages or the user will see nothing
res.sendFile(__dirname + '/index.html');
});
app.get('/msg', function(){
msg.push(req.query.msgContent);
res.redirect("/");
});
app.listen(3000, function(){
console.log("Server is running on port " + 3000);
});
The above code will work as it should but you'll see nothing in the client-side cuz you didn't render (or send msg array to client-side script to embed it). I'm just trying to make things clear to you not give you an implementation of your idea
I hope this helped you a little.

href link between two webpages on server in node.js with express package and EJS template engine

I have a server_render.js as follows. I have used express package of NPM. I have tow webpages in views directory, one is home.ejs and the other is portal.ejs. I used the EJS template engine.
var express=require('express')
var app=express()
const port=process.env.PORT || 10002
//app.use(express.static(__dirname+'/public'))
//template engine
app.set('view engine','ejs');
//homepage
app.get('/',function(req,res){
res.render('home.ejs');
})
//signin page: 127.0.0.1:10002/signin
app.get('/signin',function(req,res){
res.render('portal.ejs');
});
//run nodejs loop server
app.listen(port,function(err){
if(err){
throw err
}
console.log('server is listening on '+port+' ...')
})
views/home.ejs looks like this:
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Portal</title>
</head>
<body>
<div>You need to <a href='portal.ejs'>sign-in</a></div>
</body>
</html>
and views/portal.ejs is this:
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Portal</title>
</head>
<body>
<input name="username" id="username" type="text" placeholder="username"></input>
<input name="password" id="password" type="text" placeholder="password"></input>
</body>
</html>
I want to create a link from home.ejs to portal.ejs. I tried href="portal.ejs" however it did'nt work. I wonder what's the method.
You can't link to the actual ejs files. In your code you have declared the following paths:
//homepage
app.get('/',function(req,res){
res.render('home.ejs');
})
//signin page: 127.0.0.1:10002/signin
app.get('/signin',function(req,res){
res.render('portal.ejs');
});
This means that your express app has urls at '/' and '/signin'. On each of those two paths you have declared to render either home.ejs or portal.ejs as the output HTML.
Just point the links to '/' and '/signin' instead of the actual template files.

Processing posted data in Express + Node.js?

I am attempting to capture the information that is being sent from a form in Express and Node.js. Here are the relevant contents of my app.js and index.hjs:
app.js
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
index.hjs
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>{{ title }}</h1>
<p>Welcome to {{ title }}</p>
<form method="post" action="/">
<input type="test" name="field1">
<input type="test" name="field2">
<input type="submit">
</form>
</body>
</html>
When attempting to submit the form on http://expressserver.domain:3000, I receive a 404 error. Does anyone have any ideas on what the issue is and point me in the right direction?
Instead of using app.use, have a real POST route.
app.post("/", function(req, res) {
console.log(req.body);
res.json(req.body);
});
You need an actual route for it to kick in, and you want .post, not .use, because the latter is for all possible HTTP verbs, which means it'll try to access req.body for things that never have one (GET, OPTIONS, HEAD, etc) and crash your script.
I've found a really good example here: http://runnable.com/U0sU598vXio2uD-1/example-reading-form-input-with-express-4-0-and-body-parser-for-node-js which works.

Categories

Resources