Node JS - Access JSON from index.html on button click - javascript

I am fairly new to Node JS and I am trying to create a server that when a user navigates to http://localhost:8000/, they are routed to index.html. In that index.html file there will be a button that they can click to obtain JSON data. This JSON data is downloaded onto my own machine with the purpose of being hosted on a Node JS server. There is 6 JSON files.
My question is, can I host the JSON and the index.html on the same server without using a framework like Express? I have a solution in express, but I would like to do so without if possible.
index.html -> press button -> get JSON from server (same server?)
--- EDIT ---
It is for a university module and was given the outlined instructions. Explicitly Node.

Setup environment
mkdir server
cd server
npm init
npm install express
touch server.js index.html
mkdir public
Server.js
const express = require('express');
const app = express();
const path = require('path');
app.use('/public', express.static('public'));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(80, () => console.log("Running on: http://localhost"));
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Download JSON</title>
</head>
<body>
<h1>Download</h1>
Sample JSON
</body>
</html>
Put your JSON in the public folder structure and link to it regularly like in the HTML example above.

you can check on express js about static file.
for example:
app.use('/static', express.static('public'));
more information in:
https://expressjs.com/pt-br/starter/static-files.html

I was overcomplicating the question received. I was told to just use http and fs libraries and access JSON like, localhost/8080/path/to/json.
Apologies for the question.

Related

Why is styles.css showing canceled in Developer Tools?

I'm trying to send my 'index.html' file as a response to my local server and within that index.html, there is a link to an external CSS file.
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req,res){
res.sendFile(__dirname+"/index.html");
});
and I've included the link in HTML head element like below:
<link href="styles.css" rel="stylesheet" >
Now the problem is that the 'styles.css' file is not loading up on the page. And on the Network section of the Chrome developer tools, it is showing status: canceled in front of the 'styles.css'.
Here is the screenshot of the canceled status showing for styles.css
Why is this happening and what is the solution to it? I've tried other people's solution of deleting the cache, but it doesn't work.
EDIT: Here, I have the exact same problem , and I've tried their solutions too, but it won't work
EDIT2: As I tried #wilkoklak's solution , It's still the same error
I just added the whole thing from the Bootstrap examples so don't really think that would be a problem
You have to serve the css file as well!
You can do this by using express.static
Create a folder named css and move your styles.css there
Your project structure would look similiar to this
project/
css/
styles.css
server.js
index.js
Then add this middleware:
app.use(express.static('css'))
This middleware will look for any match with files inside css folder, and send them in response.
When you GET / (when you open your webpage), the browser also sends GET /styles.css to your server. There was no route handler for /styles.css in your app. express.static does that for you
The problem of css not being loaded can be solved by using express.static and a dedicated static folder (Example: www) for static files.
Here is the working example using express.static:
Step 1: Put static files (index.html, styles.css in a static folder named www)
Folder structure:
/nodejs-web-demo
--> server.js
/www
--> index.html
--> styles.css
Step 2: Create the index.html and styls.css files in www (static) folder
File name: www/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/styles.css">
<title>Expressjs website</title>
</head>
<body>
<p class="my-style">Hello! How are you doing?</p>
</body>
</html>
File name: www/styles.css
.my-style{
color: blue;
}
Step 3: Use express.static to serve files from static folder
const http = require('http')
const express = require('express')
const path = require('path')
const app = express()
app.use(express.static("www"))
app.use('/', function(req,res) {
res.sendFile(path.join(__dirname + '/www/index.html'))
})
const server = http.createServer(app)
const port = 3000
server.listen(port)
console.log('Web server started on port # ' + port)
Output:
> node server.js
Web server started on port # 3000

React app is not rendering at all when loading HTML page that contains it

I have a small react app that I've built using webpack, it compiled to /dist/bundle.js. I then have an express server to serve an HTML file the references my bundle.js. This way when I connect to my express server it will contain my React app. The HTML file being served by express is the following:
<!DOCTYPE html>
<html>
<head>
<title>The Minimal React Webpack Babel Setup</title>
</head>
<body>
<div id="app"></div>
<script src="./dist/bundle.js"></script>
</body>
</html>
But when running locally and opening this in a browser nothing shows. When inspecting the source I can see the HTML file is there, but nothing is showing on the page.
My server.js is the following:
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
Why can't I see my React app? Thanks for any help!
When inspecting the page I see the following (can't really copy & paste so added a screenshot):
You need to include access to the static assets on your server.
app.use(express.static('dist'));// put the correct folder here
https://expressjs.com/en/starter/static-files.html

Cannot GET /blah.html - .ejs can't load html?

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".

How do I include an external JavaScript file when serving an HTML file with a response object in expressjs?

My express app serves an HTML page from my disk upon the initial GET (i.e., if I hit "http://localhost:3000/" in the browser). Now I would like to access a JavaScript file which is in the same location in the disk as the HTML file. When I try to include it in 'index.html' by using
<script src="/myJavaScriptFile.js" type="text/javascript" ></script>
or
<script src="./myJavaScriptFile.js" type="text/javascript" ></script>
or
<script src="~/MyAbsolutePath/myJavaScriptFile.js" type="text/javascript"</script>
it doesn't work. The myJavaScriptFile.js file is never reached.
My express app looks like this:
var express = require('express')
var testMethod = require('./test')
var app = express()
app.use(bodyParser.urlencoded({ extended:false }));
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
app.get('/', function (req, res) {
console.log('In /');
res.sendFile(__dirname + '/index.html');
})
Express app is serving 'index.html' using the reference path '__dirname' + '/index.html' using res.sendFile function. (I am beginning to feel that this is a bad way of doing it. Please let me know if you think so too).
Also as we can see in the express app, an external JavaScript file called 'test' which is in the same location as 'index.html' and 'express.js' is being included without any issues. Could anyone please shed light on what's actually happening in the background? What exactly would be reference path for the JavaScript file that I can give in my 'index.html' if it is being served by express app? Thank you.
Serving files, such as images, CSS, JavaScript and other static files is accomplished with the help of a built-in middleware in Express - express.static.
Pass the name of the directory, which is to be marked as the location of static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this:
app.use(express.static('public'));
Now, you will be able to load the files under the public directory:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
More Detail Here
Happy Helping!

Loading local jquery.js file in node js

I want to load local jquery file in my node js chat application.I have searched a lot but i cant find a proper solution.
<!doctype html>
<html>
<head>
<title>Socketio</title>
</head>
<body>
<!--This wont work -->
<script src="/socket.io/jquery.min.js"></script>
<!--This will work -->
<script src="/socket.io/socket.io.js"></script>
</body>
</html>
I just copy jquery.js file to socket.io folder.The socket.io.js file loads properly but jquery file didnt.Please help me
Here is my index.js file
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
server.listen(3000, function(){
console.log('listening on *:3000');
});
Finally I found the answer.I simply load the jquery file from localhost by this way http://localhost/assets/jquery.min.js.
app.use('/assets', express.static('assets'))
Put your jquery.min.js file in relative "/assets/jquery.min.js" path, then access as http://localhost/assets/jquery.min.js
"localhost" could be your ip address also.
Personally, I need this because I need a completely self contained demo to run independant of an available internet connection. Murphy's law is alive and well come conference time.
You might want allow Express framework to render HTML and pass in the static jQuery files. That's how I would do it.
This page explains how you can restructure your app to serve jquery files through the node routes instead of HTML code.
app.get('/jquery', function(res, req){
res.sendFile(__dirname + '/jquery.js');
});
This is what worked for me. (inside app.js)
const express = require('express');//path to express module
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
My file structure looked like this:
server.js
app.js
> public
index.html
> assets
> js
jquery.min
Then import jquery from index.html like normal:
<script src="assets/js/jquery-3.3.1.min.js"></script>
One workaround is to use the online source file link.
Try loading the jquery using the following,
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
That works fine at my end.

Categories