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/')));
Related
Beginner here, please point me in the right direction! So, I used express static and can see all my static files correctly in "sources" and the CSS applies via localhost:5050. However, when I directly open my endpoint e.g. http://localhost:5500/users, I cannot see the files anymore and no more CSS is applied. I wrote requests for each specific endpoint too, of course. Does this have anything to do with the way I serve static files in my code? I can't for the life of me figure out why there are no errors in the console and network tab but the styles do not apply and the classes set in my script also do not show up via the elements page in the dev tools when I open any of my endpoints. What could be the problem if everything is working via index? Do I need to configure static files for each API endpoint somehow too?
note: I also console.logged the path and could see the path is correct - / also serves the static files correctly so I assume the issue lies somewhere else? I also tried app.use('/users',express.static(path.join(__dirname, '..', '..', 'public')));
and could then see all static files via that endpoint but the whole endpoint functionality I set later in the code broke & app.use(express.static(path.join(__dirname, '..', '..', 'public'))); should normally allow public folder access from all endpoints, right?
HTML tags:
<link rel="stylesheet" href="/css/style.css" type="text/css">
<script src="./js/bundle.js"></script>
--> also tried with js/bundle.js & other paths.
server.js:
import express from 'express';
import path from 'path';
import axios from 'axios';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
const app = express();
const port = 5500;
// Serve static files from the public folder
app.use(express.static(path.join(__dirname, '..', '..', 'public')));
// Route for serving the index.html file
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '..', '..', 'public', 'index.html'));
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
This is my folder structure:
public/
index.html
css/
style.css
js/
bundle.js
src/
client/
script.js
server/
proxy.js
server.js
When you use code like this:
app.use(express.static(path.join(__dirname, '..', '..', 'public')));
Means that every request goes through express.static middleware.
Static middleware get path from the URL and tries to match a static file in public directory to this path. Let's consider several examples:
GET https://localhost:5500/foo/bar.html -> would be converted to /public/foo/bar.html
GET https://localhost:5500/ -> public/index.html
GET https://localhost:5500/users/ -> public/users/index.html
If you replace app.use(express.static(...)) on app.use('/users', express.static(...)) then express.static would be called only on /users/... requests:
GET https://localhost:5500/foo/bar.html -> not called
GET https://localhost:5500/users/ -> public/index.html. Note, /users prefix is removed when express.static convert URL's path to file path.
So this should explain:
I also tried app.use('/users',express.static(path.join(__dirname, '..', '..', 'public'))); and could then see all static files via that endpoint
Goes next:
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '..', '..', 'public', 'index.html'));
});
applies only on / request, so if you make request on /users express returns 404. If you want fallback on index.html every request that didn't match any previous middleware you should use:
app.use((req, res) => {
res.sendFile(path.join(__dirname, '..', '..', 'public', 'index.html'));
});
And the last ./js/bundle.js:
<script src="./js/bundle.js"></script>
this is relative URL it means if you open page /users/index.html and render such HTML then browser will make request on /users/js/bundle.js. In you case I guess you want to make request always on /js/bundle.js so you should replace it on absolute path /js/bundle.js like you did for CSS
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
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".
Following is a small server (app.js) which is is simply calling index.jade file to add jquery.js, underscore.js and backbone.js for later use. But its not working.
My directory structure is:
base
app.js
public
jquery.js
underscore.js
backbone.js
theapp.js
views
index.jade
My app.js file is:
var express= require("express"),
http = require("http"),
path = require("path");
var app= express();
app.use(express.static(__dirname+ "/public"));
app.get("/", function(req, res){
res.render("views/index.jade");
});
app.listen(3000);
My index.jade file is:
#main
script(src= "jquery.js")
script(src= "underscore.js")
script(src= "backbone.js")
script(src= "theapp.js")
When I run localhost:3000 in the browser, it says: Error: Failed to lookup view "views/index.jade"
(Localhost is working fine with another node.js program)
Please help. Thanks a lot!
Dont include the .jade
res.render("views/index");
Assuming your view engine is already setup to use Jade. (app.set('view engine', 'jade');)
You also probably dont need to specify the "views" folder, check for the line
app.set('views', path.join(__dirname, 'views'));
in your app.js - this is the root directory for your views, so you'll only need:
res.render("index");
I think this is probably just a misunderstanding of how to do this on my part but its bugging me and I haven't found anything to answer the problem.
I have a static site where my file structure is
--node_modules
--index.html
--server.js
--app.js
my server.js is simple its just
var express = require("express");
var cors = require("cors");
var app = express();
app.use(cors());
app.use(express.static(__dirname + '/'));
app.get('/question', function(req, res){
res.send(req.body);
});
// Start the server on port 3000
app.listen(process.env.PORT || 3000);
// Print out a nice message so you know that the server started
console.log('Server running on port 3000');
and my bootstrap and angular WORKS...your probably wondering what the problem is....
So I have a 2nd site and I building and thought I would organize my stuff a little better. My file structure is
--node_modules
--public
|---index.html
|---app.js
--server.js
The only difference in my server.js is
app.use(express.static(__dirname + '/public'));
my bootstrap and angular is referenced in index.html like
<script src="../node_modules/angular/angular.js"></script>
<script src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
This DOESN'T work!...now I know I could just do it the first way or use a CND but I was wondering if anyone could educate me as to why and what I am doing wrong.
All help and education is greatly appreciated.
Angular and Bootstrap probably shouldn't be in node_modules unless you are using Browserify. Express won't serve any static files that aren't under the express.static root, so you can't use ../ relative paths if they go higher than public/.
That is, you need to move everything that you want to be public somewhere under public/ including index.html and the JavaScript libraries you will use.