Express static won't load CSS files from root - css

My app is loaded from a url such as : server.com/pdf/12345. When it is looking for the static files, it tries to GET /pdf/12345/assets/css/stylesheet.css and 404s. I can't figure out how to tell it to look for /public/assets in the root. Tried a number of different express.static configurations.
my directory structure looks like this:
public
--assets
----css
views
--partials
----header.ejs
routes
--api.js
server.js
server.js looks like this (minus the requires for clarity):
app.use('/', routes);
app.set('views', './views');
app.set('view engine', 'ejs');
app.use('/public', express.static(path.join(__dirname, 'public')));
http.createServer(app).listen(port, function() {
})
My partials/header.ejs contains link to stylesheet

You should write it like this instead:
app.use(express.static(path.join(__dirname, 'public')));
If you start with app.use('/public' you are telling express to only mount the function on the path /public, in your case i guess if the url starts with server.com/public. But since that is not the case, express.static() never fires.

Related

Next.js on vercel – How to add a page under /index that is not the homepage

I’m building a website with Next.js and I need to add a page called "Index" under xyz.com/index
It works fine locally but when I deploy the website to vercel, /index shows the home page which is located under xyz.com/
Is there a way to make this work through rewrites or configuration on vercel?
Would you try to create a folder named Index, then under Index folder create js file called index.js.
You can see this image--
As of now (next 12.0.3) the solution that works for me is using a rewrite:
Name the page something like "indexPage":
/pages/indexPage.js
Rewrite /index to /indexPage:
In next.config.js:
module.exports = {
// …
async rewrites() {
return [
{
source: '/index',
destination: '/indexPage',
},
]
},
// …
}
Using the following folder structure only worked locally for me but not when deployed to vercel:
/pages/index/index.js

Loading static files in Express

I have been trying to get my node.JS file to serve my HTML app with static CSS and JS files included too but have ran into great difficulties (the HTML file is loading, but with no styling). From my searching it seems the main recommended method is to add the Express middleware to your node.JS and then add this line:
app.use(express.static(path.join(__dirname, 'static/')));
Before I go on too much further I will show you my directory set-up:
-static
-images
-favicon
-favicon.png
-logo.png
-style
-design.css
-theme.css
-w3.css
-source
-client
-style.js
-node_modules
-...
-index.html
-root.js
-package-lock.json
-...
The 'root.js' file is my node.JS file that I am running and it serves the 'index.html' page, but all the CSS and JS files my HTML page links to come up with this sort of error...
The stylesheet http://localhost:8080/static/style/design.css was not loaded because its MIME type, "text/html", is not "text/css".
Here is one example of a line in my 'index.html' where I try to link to that CSS file...
<link rel="stylesheet" type="text/css" href="static/style/design.css">
...and here is where 'index.html' is served in my 'root.js' file...
http.createServer(function (req, res) {
fs.readFile('index.html', function (err, data) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
return res.end();
});
}).listen(8080);
I am not too sure where I am going wrong as most guides on the topic seem to imply that when I add in the magic '__dirname' line to my node.JS that everything is meant to resolve itself. When I just run my HTML page locally by opening it in Chrome or Firefox it works fine. I am hoping you might be able to explain to me where I am going wrong, thank you.

Link css stylesheet with express.static problem

I'm just learning, so need some help with something.
When I try to load my html file on my local server it doesn't load my styles.css file.
I used the express.static on my "public" folder and modified the path of the styles.css in the html file. Some help would be great . Thanks.
The folder paths: css
C:\Newsletter-Signup\public\css\styles.css
html file that i tryed to load with applied .css on it:
C:\Newsletter-Signup\public\signup.html
!(https://imgur.com/PJO7J4H)
this is my app.js file:
const app = express();
app.use(express.static("public"));
app.get("/", function(req, res){
res.sendFile(__dirname + "/signup.html" );
});
app.listen("3000", function(){
console.log("server started on port 3000");
});
and this is my link to styles.css that doesnt load:
< link href="css/styles.css" rel="stylesheet" >
Here I am trying to present you a generic solution.So this may be helpful to fix the issue, which occurs during your code attempt.
When generating the express app project, I used the command npm install -g express-generator which recommended in Express Js official site. From that, I could easily create the folder structure for the express app.
.pug file format
By default the generated express app only allows you to render .pug file format instead of .html file. Express-generator installs pug node module via npm install pug -- save while installs other required dependencies. After installs pug dependency you are allowed render .pug files locate in the root using localhost URL.
app.js
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next) {
res.render('<pug file name>', { title: 'Express' });
});
Set your current directory as app root and run the command npm start from your terminal and visit the URL http://localhost:<Port Name>/
Then you can see the rendered .pug file.
Get support for .html file format
Since Express Js supported .pug file format, you need to install ejs node module to get support for the .html format.
npm install ejs --save
Then need to update app.js file content as below
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next) {
res.render('<html file name>', { title: 'Express' });
});
Now you will see, .html file is rendered properly.
Add a stylessheet to express app
In app.js file, a directory path is already set for static files as shown below.
app.use(express.static(path.join(__dirname, 'public')));
It means that the public folder is set as static file directory.
So, when linking a stylesheet inside head tag, a relative path for stylesheet should be stated as 'stylesheets/style.css.
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css">
</head>

Vue js deploying in production seems harder then it is

I've created simple Vue JS App using Vue-cli 3. I have a digitalocean droplet with Nginx + php.
My goal is to host Vue App on the same droplet.
I have already tried:
Add certain location / to nginx conf.
Used this simple node server: https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations
And what I get i sUncaught SyntaxError: Unexpected token <:
Interesting thing, when I use npm run build to make production resources into dist directory and use php -S localhost:8080 it is hosted like a charm. But the same thing with simple node js server causes the result on the screenshot above.
I've been struggling for 2 days straight. Halp me please.
I was struggling with the same issue. The problem was that when the browser requests the javascript and css files, the contents of the index file is sent instead.
Solved it by following step 3 of this tutorial.
Since Vue is only a frontend library, the easiest way to host it and
do things like serve up assets is to create a simple Express friendly
script that Heroku can use to start a mini-web server. Read up quickly
on Express if you haven’t already. After that, add express:
npm install express --save
Now add a server.js file to your project’s root directory:
// server.js
var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');
app = express();
app.use(serveStatic(__dirname + "/dist"));
var port = process.env.PORT || 5000;
app.listen(port);
console.log('server started '+ port);
After that, since the idea is to serve index.html in the first place, I borrowed this idea and added the following to my code (notice I used sendFile if the request is html):
app.use((req, res, next) => {
res.status(404)
if (req.accepts("html")) {
res.sendFile(path.join(__dirname + "/dist/index.html"))
return
}
if (req.accepts("json")) {
res.send({error: "Not found"})
return
}
res.type("txt").send("Not found")
})
A little bit late, but I have used this to sendFile index.html up on 404 response.
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(404).sendFile(path.resolve(__dirname, "dist", "index.html"));
})
Explanation:
err will be defined when the request is erroneous. res.status will set the status to 404 code and the app will sendFile the resolved index.html. (Notice that I used __dirname and path.resolve together to build an absolute path to be safe.

Why isn't the whole folder served on the root when using UseFileServer in OWIN?

I'm building a simple demo app where I want to use the StaticFile extensions. To configure it I have the following code:
app.UseFileServer(new FileServerOptions()
{
FileSystem = new PhysicalFileSystem(#".\content"),
RequestPath = PathString.Empty,
EnableDefaultFiles = true
});
In the folder content I have an index.html which is server directly when I visit / as expected, but files are not served as expected.
content
index.html
app
lib
something.js
This is the file structure I have and what I want is to access something.js at the url /app/lib/something.js but with the code I have now I have to use /content/app/lib/something.js which I don't want. Why does the index.html get served directly when I visit / but not when I go to /index.html and the same goes for the js file.

Resources