Problem with static routing in Node.js using express - javascript

I am having an issue with some custom routing code, it all works fine and is in sync with the client-side view routing I do, but as soon as I have a subpage, it doesn't route my static files correctly.
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
Rather than giving me a file from the root directory, it'll serve it as if it were from the subfolder.
Example: i go to http://localhost/sign-up, and files loading in my index file from /scripts are loaded, but if i go to http://localhost/sign-up/2, it'll attempt to load the script from /sign-up/scripts
const express = require('express');
const path = require('path');
const app = express();
app.use('/views', express.static(path.resolve(__dirname, 'frontend', 'views')));
app.use('/styles', express.static(path.resolve(__dirname, 'frontend', 'styles')));
app.use('/scripts', express.static(path.resolve(__dirname, 'frontend', 'scripts')));
app.use('/media', express.static(path.resolve(__dirname, 'frontend', 'media')));
app.get('/*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'frontend', 'newSite.html'));
});
app.listen(process.env.PORT || 1234, () => console.log('Server is now running...'));
To manage this I have been following these tutorials by DCODE on youtube, but I can't see anything amiss:
https://www.youtube.com/watch?v=6BozpmSjk-Y
https://youtu.be/OstALBk-jTc

Resources loaded in the sign up folder should use URLs beginning with a '/' character, to make them relative to the site root, e.g.
src="/scripts/modulefile.js"
href="/css/stylesheet.css"
href="/media/image.png"
and not urls relative to the signup folder - which they will be if the leading '/' is omitted.

You don't need multiple routes to serve your static contents, and the static method of express do such kind of tasks for you:
// If your 'public' or 'static' directory is one of root directories
app.use(express.static(process.cwd() + '/public'));
// so all these requests will be served:
// -> /public/styles/custom.css
// -> /public/scripts/pollyfils.js
// -> /public/media/logo.png

Related

Landing page keeps returning static files in express

I am trying to use static files in my project, but when the user makes a get request to my "/" landing page. I want to send non-static things like a json. But for some reason it just automatically sends my index.html in my static file.
const express = require("express");
const app = express();
app.use(express.static("public"));
app.get("/", (req, res) => { //This sends the user to the index.html even tho i want to send 123
res.send("123");
});
app.listen("3000");
As your code is written, the express.static() middleware looks at the / request, finds an index.html file in the public directory and serves that as the response for the / request. This is a feature of express.static() that is causing a conflict for you with your custom route for "/".
You have at least four choices for a solution here:
You can specify an option for express.static() to disable the index.html feature so it will avoid the "/" route and pass control on to your subsequent route handlers.
You can move the express.static() middleware AFTER your app.get("/", ...) route so that your custom route gets first dibs at the request.
You can remove the index.html file from your public directory so express.static() won't find it. Using a template system for all your HTML files that locates all HTML template files in some other directory that express.static() can't see (such as a views directory) would cause this to happen too or just moving it to some private directory and using it from your code from the private directory would work too.
Give ALL your static resources a common path prefix so there is never a URL conflict between static resources and custom route handlers.
The first option (disable index.html feature in express.static()) would look like this:
const express = require("express");
const app = express();
// disable index.html feature
app.use(express.static("public"), {index: false});
app.get("/", (req, res) => {
res.send("123");
});
app.listen("3000");
The second option (change the order of route definitions/middleware) would look like this:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("123");
});
// put this after custom route definitions so they take precendence
app.use(express.static("public"));
app.listen("3000");
The fourth option (give all static resources a common path prefix) would look like this:
const express = require("express");
const app = express();
app.use(express.static("/static", "public"));
app.get("/", (req, res) => {
res.send("123");
});
app.listen("3000");
With this fourth option, you'd then have to prefix all your static URLs with the static prefix (which you can make anything you want) and thus "/" would never be a match for express.static().
Is there any particular reason that you have an index.html file inside your public directory and are serving something else? The convention is serve static assets such as CSS, JS, images etc. from your public folder, and HTML / templates in folder which would be a sibling of public such as views.
The browser will always default to rendering an index.html file if it is found in the root of the public directory. Move the HTML file to a separate folder and the route should work
app.use is a middleware, so whenever you're running a app, it always first go through the middleware, Try the below code
const express = require("express");
const app = express();
app.get("/", (req, res) => { //This sends the user to the index.html even tho i want to send 123
res.send("123");
});
app.use(express.static("public"));
app.listen("3000");

Returning a page through HTTP with express

I have a folder called "Public" which contains an index.html file a long with some JavaScript and library files. When someone tries to access the products path (mydomain.com/products) I want to display that index.html file, but the client also needs to receive all the JavaScript and libraries. Here is the code for how I initially handle the HTTP request.
const express = require('express')
const app = express()
const bodyParse = require('body-parser')
const productRoutes = require('./api/routes/products')
const orderRoutes = require('./api/routes/orders')
app.use(bodyParse.urlencoded({extended: false}))
app.use(bodyParse.json())
// Routes which handle requests
app.use('/products', productRoutes)
app.use('/orders', orderRoutes)
In the products.js file, I continue the routing like this:
const express = require('express')
const router = express.Router()
router.get('/', (req, res, next) => {
/*res.status(200).json({
message: 'Handling GET requests to /products'
})*/
res.status(200).render("../../public")
})
The code I've commented out works perfectly fine, but I'm struggling to respond with the "public" folder page. I can't remember everything I've tried, but using .render or .sendFile on the "public" directory has not worked for me.
When I try to access the /products route, I'm hit with an empty error message. As it fails to return anything in the /products route, in continues down the file to an error handler. The error message is empty.
Any ideas on how to display the page with all the folder contents would be great!
Try: app.use('/products', express.static('public'))
This makes your "public" directory viewable from the /products route.
express.static() docs
You must config path for express static by :
//app.js | server.js
app.use(express.static(__dirname + '/public'));
Then, in example you have a file as : /public/you.html
In your app, you can use that file as path /you.html
And the same with all files type *.js, *.css,...
Fix error cannot view error
Run cmd npm install ejs
Att to app.js:
app.set('view engine', 'ejs');
After that, you create 1 file error.ejs at folder views :
//error.ejs
<%=error%>
Goodluck

Express sending assets with wrong MIME type

Using Express to serve a Vue.js webpack app, I am receiving the following error after deploy:
Is my code for serving the app is the issue here?
app.use(helmet())
app.use(express.static(path.resolve(__dirname, '../client/dist/static')));
app.all('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '../client/dist', 'index.html'));
})
Otherwise isn't express.static supposed to automatically assign content types to the static files?
You get this message also when the response status in 404 Not Found, so check carefully that the files actually exist from Network tab.
Network tab:
Console tab:
See a similar issue here: https://stackoverflow.com/a/48792698/258772
For some reason, had to now specify a mount path:
app.use('/static', express.static(path.resolve(__dirname, '../client/dist/static')));
Yes same problems over here.
I'm using ecstatic (still with express) now. I'm not sure if this is the solution (I'm not on the machine that made the error possible).
Will try it tommorow on the 'error' machine.
const express = require('express');
const ecstatic = require('ecstatic');
const http = require('http');
const app = express();
app.use(ecstatic({
root: `${__dirname}/public`,
showdir: false,
}));
http.createServer(app).listen(8080);
console.log('See if its cool on -> :8080');

Node JS - HTML Paths

I recently have the problem that I dont get how the paths for html in node js work. I link my index.html's scripts as normal - relative to the index.html's file (node.js file and index.html are in the same directory "res.sendFile(__dirname + '/index.html');"). But if I open it up in the Browser executed with node js it just stats "cant GET blabla" for the scripts. Instead opening it up by just clicking index.html without node js those paths work! How do I have to write html paths for node js?
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
port = Number(process.env.PORT || 3000),
server.listen(port);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
Thanks for your time! :)
Look at this:
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
You have told Node "When the browser asks for / give it index.html".
What happens when the browser asks for someScript.js?
You haven't told Node what to do then.
(You'll probably want to find a library for serving up static files rather than explicitly handling each one individually).
you should configure express to server static files, for example, put all the static files under a directory called 'public'
var express = require('express');
var app = express();
var path = require('path');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
ExpressJS to Deliver HTML Files
Render HTML file in ExpressJS
You can use
app.use(express.static(path.join(__dirname, "folder-name")));
Usually i put all my static files in a separate folder named "assets"
The I set up a static route as shown below:enter code here
app.use('/assets', express.static('assets'));
When you write:
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
It will only serve index.html file, not the other js scripts and stylesheets which you have added in your html.
There are 2 ways to solve that:
For both of them, I would suggest to use 'path' module.
Solution 1:
var path = require('path')
app.get('/path/to/js/foo.js',function(req,res){
res.sendFile(path.resolve(__dirname,'/path/to/js/foo.js')
})
app.get('/path/to/css/bar.css',function(req,res){
res.sendFile(path.resolve(__dirname,'/path/to/css/bar.css'))
})
and so on for every .css and.js file you have added in your index.html.
Solution 2:
You can create a public dir in your project's root dir. Inside which all your img, css and js files will be there.
Next,
var path = require('path')
app.use(express.static('public'))
app.get('/',function(req,res){
res.sendFile(path.resolve(__dirname,'/index.html')
})

NodeJS / Express / Mean Stack

I am new to Express and semi-new to nodejs and I am trying to run a simple app / webserver as a proof of concept. I have been stuck for hours because my server serves every file as index.html (with the content of index.html).
In my index.html I am making calls to JS files and CSS files and they are all coming back but with a 200 in the console but they are all coming back with index.html content instead of the actual content contained in them. I believe the problem is in my server.js file which is below:
// server.js
// modules =================================================
var express = require('express');
var app = express();
var mongoose= require('mongoose');
var path = require('path');
// configuration ===========================================
// config files
var db = require('../config/db');
var port = process.env.PORT || 9999; // set our port
//mongoose.connect(db.url); // connect to our mongoDB database (uncomment after you enter in your own credentials in config/db.js)
app.configure(function() {
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(express.logger('dev')); // log every request to the console
app.use(express.bodyParser()); // have the ability to pull information from html in POST
app.use(express.methodOverride()); // have the ability to simulate DELETE and PUT
});
// routes ==================================================
require('../../app/routes')(app); // configure our routes
// start app ===============================================
app.listen(port); // startup our app at http://localhost:9999
console.log('Magic happens on port ' + port); // shoutout to the user
exports = module.exports = app; // expose app
// app/routes.js
module.exports = function(app) {
// server routes ===========================================================
// handle things like api calls
// authentication routes
// sample api route
app.get('/api/nerds', function(req, res) {
// use mongoose to get all nerds in the database
Nerd.find(function(err, nerds) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err);
res.json(nerds); // return all nerds in JSON format
});
});
// route to handle creating (app.post)
// route to handle delete (app.delete)
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendfile('/Users/...../app/public/index.html'); // load our public/index.html file
//res.sendfile(path, {'root': '../'});
});
};
I have been following this tutorial verbatum: http://scotch.io/bar-talk/setting-up-a-mean-stack-single-page-application but haven't had much success.
I cannot confirm without looking at your computer but I get the feeling the paths in your application are wrong.
The crucial parts in the express setup are:
app.use(express.static(__dirname + '/public'));
and
app.get('*', function(req, res) {
res.sendfile('/Users/...../app/public/index.html');
The first rule catches and returns any static file in __dirname + '/public'.
The second returns index.html for anything else.
The problem is that your server.js is not in the apps directory (I can see this since you use ../../app/routes.js to get to routes.js) this means __dirname + '/public' is not pointing to the public directory. Which is why your static files are being served by the global rule in routes.js.
In order to fix this change __dirname + '/public' to ../../app/public, or better yet place your server.js file where it should be and update your paths.
I can also see you are using an absolute full path to index.html in routes.js instead of a relative one so it seems as if your applications needs to tidied out.
The tutorial that you are following contains this route
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load our public/index.html file
});
which explicitly defines the behaviour you described.
In this tutorial it makes sense because it explains how to build a single page application. This type of the application typically returns the same content for all the request while the actual presentation work happens on the client by the client-side library (angular in this example).
So if you what to serve more pages with different content you need to add more routes for them, just like route for /api/nerds in the example.
Update:
After clarifying that the issue is incorrectly served CSS and JS files, the proposed solution is to check the location of the server.js - it should be in the folder together with the folder "public".

Categories