I am learning Node.js and Express (version 4.11). Currently, I am trying to create a basic web app that uses a stylesheet. In an attempt to do this, I have the following HTML:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="Description">
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/public/fonts/icomoon.css" />
<link rel="stylesheet" type="text/css" href="/public/css/style.css" />
</head>
<body>
<h1 class="title">Test</h1>
</body>
</html>
When this HTML is loaded, I get 404 errors for my icomoon.css file and my style.css file. I'm confused, because I've followed the other similar post on SO. My server.js file looks like the following:
var express = require('express'); // routing-engne
var expressHbs = require('express-handlebars'); // view-engine
// Setup the app to use Handlebars as the view engine
var app = express();
app.engine('hbs', expressHbs({extname:'hbs', defaultLayout:'layout.hbs'}));
app.set('view engine', 'hbs');
// Add support for static files (css, fonts, images, etc.)
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
var viewModel = {};
res.render('/index', viewModel);
});
// Start the app on port 3000
app.listen(3000);
console.log('Ready!');
I thought the line written as app.use(express.static ... would serve up my static files. However, it is not. How do I serve up my .css files?
Thank you!
Use this:
app.use('/public', express.static(__dirname + '/public'));
Related
trying to understand why mime nosniff is blocking my static JS file?
even though its been defined as "text/javascript"
using a simple express app to call the route of the EJS.
here are the files
SERVER:
const express = require ("express");
const { render } = require("express/lib/response");
const app = express();
const path = require('path');
app.use(express.static('public'))
app.set('view engine', 'ejs'); //enabling ejs
app.set('views', path.join(__dirname ,'/views'))
app.get('/test', (req,res) => {
res.render('test');
})
app.listen(3000, () => {
console.log("LISTENING ON PORT 3000!")
})
EJS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content-type="application/javascript" >
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
hey do you think this could work?
<script type="text/javascript" src="geojson1.js"></script>
</body>
</html>
Static JS file
const inside = "in the JS file ";
console.log(inside)
getting the usual:
"The resource from “http://localhost:3000/geojson1.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)."
I have written a simple express script to serve a webpage with embedded javascript. However, the server can't seem to find any of the files that I am giving to it. What's more frustrating, sometimes it seems to work, only for it to break again when I change an irrelevant bit of code.
All of the files are where I am telling the script, but I constantly get the following kind of error:
GET http://localhost:55154/jsPsych/jspsych.js net::ERR_ABORTED 404 (Not Found)
Here is the express code:
// --- LOADING MODULES
var express = require('express');
// --- INSTANTIATE THE APP
var app = express();
// --- STATIC MIDDLEWARE
app.use(express.static(__dirname + '/public'));
app.use('jsPsych', express.static(__dirname + "/jsPsych"));
// --- VIEW LOCATION, SET UP SERVING STATIC HTML
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// --- ROUTING
app.get('/', function(request, response) {
response.render('index.html');
});
app.get('/experiment', function(request, response) {
response.render('go_no_go.html');
});
// --- START THE SERVER
var server = app.listen(process.env.PORT, function(){
console.log("Listening on port %d", server.address().port);
});
And here is the relevant bit of javascript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="../jsPsych/jspsych.js"></script>
<link type= "text/html" href="jsPsych/css/jspsych.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jsPsych/plugins/jspsych-html-keyboard-response.js"></script>
<script type="text/javascript" src="jsPsych/plugins/jspsych-image-keyboard-response.js"></script>
<script type="text/javascript" src="jsPsych/plugins/jspsych-survey-text.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
do you have to move up a directory to access jspsych.js? if not remove the ".." in your relative path to make sure that the relative path lines up with your files.
(I know this question have been asked many times in many form, but I tried a lot of solution and none work the way it should.. So maybe a solution adapted to my work would help me understand.)
Here is the structure of my project.
Here is the index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./../node_modules/bootstrap/dist/css/bootstrap.min.css">
<title>Document</title>
</head>
<body>
<nav class="navbar navbar-default ">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Brand</a>
</div>
</div>
</nav>
<script src="../node_modules//bootstrap.min.js"></script>
<script src="./../node_modules/jquery/dist/jquery.js"></script>
</body>
</html>
And here is the server/app.js. I let the res.sendFile(); empty on purpose.
//export used
var express = require('express'),
url = require("url"),
path = require("path"),
fs = require("fs");
const _port = 3000
var app = express();
app.get('/', function(req, res){
res.sendFile();
});
app.listen(_port, function() { console.log('listening port '+_port+"\n__dirname : "+__dirname)});
The purpose of the server for now is just to send the index.html, that is one level up in the public folder. when a request in made to '/'. and I CAN'T DO IIIITT,
for several reason:
-I tried to use helmet to workaround Content Security Policy.
-I tried to use the static middleware to do stuff..
-I tried to use the path.join / resolve
So is there anyone who can explain somehow how to send this public/index.html file with the bootstrap scripts/css working ?
Have a nice day
Edit:
Here is the new app.js, it render the index.html thanks to the express.static but bootstrap css/scripts are not rendered :
//export used
var express = require('express'),
url = require("url"),
path = require("path"),
fs = require("fs");
const _port = 3000
var app = express();
app.use(express.static(path.join(__dirname, '/..', 'public')));
app.get('/', function(req, res){
res.sendFile('../public/index.html',{root: __dirname});
});
app.listen(_port, function() { console.log('listening port '+_port+"\n__dirname : "+__dirname)});
You have to add static middleware just after defining your app and before other routings because it is recommended to put static middleware first.
Use the path module to join the paths since it helps to avoid issues
of operating systems working differently with slashes and backslashes.
app.use( '/' , express.static(path.join(__dirname ,'..' ,'public'));
By doing this, you can serve all your static files in the public directory including scripts and css.
If you are using express, then you shouldn't serve single file instead you can make a static folder where all your js and css lies and you can serve that whole folder and use angular for routing.
Here is sample code:
var express = require('express'),
url = require("url"),
path = require("path"),
fs = require("fs");
const _port = 3000
var app = express();
app.use('/',express.static(__dirname+'public'));
app.use(bodyParser.json());
app.listen(_port, function() { console.log('listening port '+_port+"\n__dirname : "+__dirname)});
For my web app I am using ejs with express and parse.com on the backend.
I am having an issue with adding stylesheet and all the answers to this question I was able to find are not solving my problem. I thought maybe showing my code would help to solve it.
My stylesheet directory is public/css/style.css
See below the code from cloud/app.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.set('views', 'cloud/views'); // Specify the folder to find templates
app.set('view engine', 'ejs'); // Set the template engine
app.use(express.bodyParser()); // Middleware for reading request body
var Movies = Parse.Object.extend('Movies');
app.get('/', function(req, res) {
var query = new Parse.Query(Movies);
query.find({
success: function(results) {
res.render('movie-list', { movies: results });
},
error: function(results, error) {
}
});
});
app.listen();
And here is my template, located in the views:
<html>
<head>
<title>Movies</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" type="text/css">
</head>
<body>
<h1>Movies</h1>
<ul id="categoryList" class="list-group">
<%
for (var i = 0; i < movies.length; i++)
{
var movie = movies[i];
%>
<li class="list-group-item"><%= movie.get('Movie')%></li>
<%
}
%>
</ul>
</body>
</html>
Any help would be greatly appreciated! Thank you!
Let me answer my own question. I deleted the line
app.use(express.static(__dirname + '/public'));
and left link to stylesheet in the head of my template as it is:
<link href="/css/style.css" type="text/css">
Now my stylesheet is working.
I haven't tested your code, but looking at my Parse web apps, my links to stylesheets start with /
Try changing
<link href="css/style.css" type="text/css">
to
<link href="/css/style.css" type="text/css">
Good luck!
Please include following in your app.js:
var path = require('path');
app.use('/css',express.static(path.join(__dirname, 'public/css')));
Now reference your css as : <link href="css/style.css" rel="stylesheet">
It should work for you.
But i think it's important to understand about express static middleware and why i am telling you to include those lines.
express.static middleware is responsible for serving the static assets of an Express application. How it works:
Serve static content for the app from the "public" directory in the
application directory
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
Mount the middleware at "/static" to serve static content only when
their request path is prefixed with "/static"
// GET /static/style.css etc.
app.use('/static', express.static(__dirname + '/public'));
Serve static files from multiple directories, but give precedence to
"./public" over the others
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/files'));
app.use(express.static(__dirname + '/uploads'));
So these are three different ways you can use express static middleware.
Assuming that you use the express generator (npm install express-generator -g), any style have to be added to the /public/stylesheets/style.scss files
I'm having a small problem with my project.
I'm using node and express for a little webpage .. it is rendering the html page, but the javascript file (test.js) is not sent to the user ..
<!doctype html>
<html>
<head>
<title>Spektrum</title>
<script src="test.js"></script>
<meta name = "viewport" content = "initial-scale = 1, user-scalable = no">
<style>
canvas{
}
</style>
</head>
<body>
<!-- some stuff -->
</body>
</html>
Node.js file:
var http = require('http'),
fs = require('fs'),
express = require('express'),
app = express();
app.use(express.bodyParser());
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
// .....
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
Any idea how to send the javascript file with the html file to the user?
Greetings,
JS
you need to use static middleware to serve file (test.js needs to exist)
example:
// GET /javascripts/jquery.js
// GET /style.css
// GET /favicon.ico
app.use(express.static(__dirname + '/public'));