Node js server doesn't show images in html file - javascript

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/

Related

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,

Sitemap xml in node for google console

Im trying to add a sitemap at Google Search Console.
I have this code:
Route
router.get("/sitemap", function(req, res){
res.render("sitemap.ejs");
});
Sitemap.ejs
<html>
<head>
<title>Sitemap</title>
<link rel="alternate" type="application/rss+xml" title="" href="sitemap.xml" />
</head>
<body>
</body>
</html>
But when i try to add the sitemap to google it says that the sitemap cant be in html format.
How can i make it valid to Google Search Console?
Solution
var path = require("path");
router.get('/sitemap.xml', function(req, res) {
res.sendFile(path.join(__dirname, 'path', 'sitemap.xml'));
});

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.

Grab images from JSON file with NodeJS

I am testing an Electron app. I want it to grab images from this website. That website has a JSON file that has this code.
How can I get those images and put them in an img tag?
So far I have this code:
var request = require('request');
request("http://www.pgbovine.net/photos/json-files/boston.json" , function(error, response, body) {
body = JSON.parse(body);
console.log(body);
function addImg(arr) {
myImg = arr[0]["filename"];
var theImg = document.getElementById("image");
theImg.innerHTML = myImg;
}
And this HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pics</title>
</head>
<body>
<img id="image">
<script type="text/javascript">
require("./memes.js")
</script>
</body>
</html>
The problem is, that code doesn't do anything! So how can I grab an image from the JSON file above and put it into and img tag? (Using NodeJS or vanilla JavaScript)
You are simply adding to the img tag the filename, but you need to add the entire image url not just the filename (like IMG_2914.JPG).
I tried http://www.pgbovine.net/photos/IMG_2914.JPG but got 404 error.
You should be modifying the 'src' attribute of the img html tag to point to the URL or relative path of the image in question.
You would call the 'setAttribute' method on theImgvariable to do this.
Based of the structure of that JSON response, you may also want to set the 'alt' attribtue to the 'description' string of each image object, which would provide a simple mouse-over text.
Note that the JSON that you're talking about here doesn't actually contain the image, just a string that is the filename of the image.
Based on the website you seem to be attempting to scrape, to grab things from the boston image gallery, you would need to append the filename to the following string:
http://www.pgbovine.net/new-galleries/boston/images/
Like so:
<img src="http://www.pgbovine.net/new-galleries/boston/images/IMG_2914.JPG">

Node Server Not Loading CSS File

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.

Categories

Resources