I cannot load my Static JS in an Express server - javascript

I'm pretty miffed with this one, it seems to be a well answered issue, and my code seems legit, but I'm not seeing the problem . . .
I have a .js file to connect to my survey page, and have it added as such at the bottom of the <body> tag:
<script type="text/javascript" src="/static/questions.js"></script>
In server.js I've tried this:
app.use(express.static('public'));
app.use(express.static('data'));
app.use('/static', express.static('public'));
app.use('/static', express.static('data'));
really covering the bases there . . . 'public' is where the html pages lie, data where my json and .js files.
Tree:
root
-app
--data
--public
server.js
but I am continuing to get a failure to load js error.
What gives, man?

That is because you didn't send the js file to the user when a request is received in the server
Eg: we need js file named as public.js
file path: ui/publish.js
request : http//:localhost:4000/ui/publish.js
app.get('/ui/publish.js', function (req, res) {
res.sendFile(path.join(__dirname, 'ui', 'publish.js'));
});
Try this.

Try this.
Structure
root
-app
--data
-- a.js
-- b.js
--public
-- a.html
server.js
app.use(express.static('public'));
app.use(express.static('data'));
Now your url for accessing a.js is http://localhost:8080/a.js and html http://localhost:8080/a.html

<script type="text/javascript" src="/questions.js"></script>
you should modify your script tag like this and add the below line in server.js
app.use(express.static(path.join(__dirname, '/app/public')));
put your js files in the /app/public folder

Related

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

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.

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

Express, Wildcard-Subdomains, and sendFile()

I'm using Wildcard Subdomains on my Express server so that when users go to name.example.com, or request something from the API from that subdomain it all works well. (Navigating to name.example.com/api works correctly)
However, actually navigating to name.example.com needs to serve an index.html file; I'm using the code below as a catchall, but any files that are linked to inside the HTML file (like a stylesheet or JS file) are being served with the contents of index.html.
// routes/routefile.js
router.get('/_sub/:name/*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'public', 'index.html'));
});
My file structure:
Project/
|_ routes/
|_ public/
|_ server.js
If there's a better package I should be using, please let me know!
Thanks!
This works:
app.use('/_sub/:name/', express.static(path.join(__dirname + '/public/')));

Files won't load if in root directory?

I have a weird problem with my file structure. For some reason, after creating the server and running it, I can't get the index.html to run unless it is in a folder. The browser just shows "Cannot GET /". The same can be said for my JS files that are being used in the index.html. Unless they are in folders and not in the root directory itself, they will not load into index.html. Is this normal or is this because of how I have my server.js file set up?
Here's the code:
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, './views')));
app.listen(8000, function() {
console.log("Listening on Port 8000");
})
The folder/file structure is:
Root Directory
- node_modules
- views
-js
-script.js
- pages
-about.html
-contact.html
-home.html
- index.html
- server.js
The problem is when the file structure is:
Root Directory
- node_modules
- pages
-about.html
-contact.html
-home.html
- index.html
- script.js
- server.js
The express.static is also pointing to pages instead of views.
Any suggestions on why this is the case? Thanks in advance.
simply, express.static(path.join(__dirname, './views')) will serve all files in folder views
if you go to /pages/index.html . this will check folder view for /page/index.html if exist index.html, it will serve you this file else it will check if you have any handle route logic
You can set multi serve-static.

Referencing java script files from html in nodejs server

I am having a node js server that serves index.html when user hits localhost:3000/
app.get('/', function (req, res){
res.render('index.html');
});
However i cant figure out how i can refer to myscript.js javascript file from within the index.html.
<script src="script/my_script.js" type="text/javascript"></script>
I am calling a click button function from this file, but at run time this call gives 404. Please let me know how i can refer to a javascript file from within index.html in a nodejs server setup.
You can set up a static directory in which express will serve files as-is. For example:
app.use("/", express.static(__dirname + '/public'));
You can then create a "public" directory in your app root, and move your "script" folder inside. Any files (such as javascript, css) inside will be served directly to clients.
Docs

Categories