Static files with Express - css

I am trying to link a stylesheet in a jade template, and am getting a 404. I have the exact path to the stylesheet, and have my app configured to serve up static files from my 'static' directory, but I am still getting a 404 ? Also why do static files need to be served up ? Why can't they just be linked to in your templates ?
'use strict';
var express = require('express');
var app = express();
app.set('view engine', 'jade')
app.set('views', __dirname + '/templates')
app.listen('3000', function(){
console.log('Running on port 3000');
})
app.use(express.static(__dirname + '/static'));
// Routes
app.get('/', function(request, response){
response.render('index')
});
app.get('/blog:id', function(request, response){
response.send('This is the blog page.')
})
app.get('/about', function(request, response){
response.send('This is the about page.')
})
Jade template
html
head
link(rel="stylesheet", href="../../static/css/normalize.css")
link(rel="stylesheet", href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css", integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7", crossorigin="anonymous")
link(rel="stylesheet", href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css", integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r", crossorigin="anonymous")
body
div.hero(style="width: 100%; height: 400px; background-color: blue")
h1(style="color: white;") This is the landing page !
script(src="https://code.jquery.com/jquery-2.2.3.min.js", integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=", crossorigin="anonymous")
script(src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js", integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS", crossorigin="anonymous")

You can have your css file url relative to the static folder
link(rel="stylesheet", href="/css/normalize.css")

Related

How to return html file on specific path in deno?

I have a very basic deno app with oak module to build the http server. I want to send a http file, the index.html, only when the path is / (not /anyotherpath).
From oak's github I have this code
app.use(async (ctx, next) => {
try{
await ctx.send({
root: `${Deno.cwd()}/public`,
index:"index.html",
});
}catch{
await next();
}
});
But how do I send the html only for that given path? I also tried with Router
from oak but I couldn't figure out how to serve the html file.
If you only want to respond with the index.html file, and only at the root path /, you can do it the following way:
I've included comments for almost every line of the server example. Feel free to ask any questions in a comment if something is unclear. Be sure to reference the Oak documentation.
./public/index.html:
<!doctype html>
<html lang="en">
<head>
<title>Hello world</title>
</head>
<body>
<h1>Hello world</h1>
</body>
</html>
./main.ts:
import * as path from "https://deno.land/std#0.146.0/path/mod.ts";
import { Application, Router } from "https://deno.land/x/oak#v10.6.0/mod.ts";
// The directory of this module
const moduleDir = path.dirname(path.fromFileUrl(import.meta.url));
// The public directory (with "index.html" in it)
const publicDir = path.join(moduleDir, "public");
// A helper function to get the file contents
// of a specific file path in the public directory
function getPublicFile(...filePath: string[]): Promise<Uint8Array> {
return Deno.readFile(path.join(publicDir, ...filePath));
}
// Create a router
const router = new Router();
// Only handle GET requests to the "/" path
router.get("/", async (ctx, next) => {
// Set the contents of the "index.html" file to the response body
ctx.response.body = await getPublicFile("index.html");
// Set the appropriate resopnse type for HTML
ctx.response.type = "text/html";
// This isn't technically needed here, but it's good practice
// because other middleware might need to run in more complicated routes
await next();
});
// Create the app
const app = new Application();
// Use the router from above
app.use(router.routes());
app.use(router.allowedMethods());
// This is not needed, but is potentially nice for yourself in the console
function printStartupMessage({ hostname, port, secure }: {
hostname: string;
port: number;
secure?: boolean;
}): void {
const address = new URL(
`http${secure ? "s" : ""}://${
hostname === "0.0.0.0" ? "localhost" : hostname
}:${port}/`,
).href;
console.log(`Listening at ${address}`);
console.log("Use ctrl+c to stop");
}
// Run the function above when the server starts listening
app.addEventListener("listen", printStartupMessage);
// Start the server
await app.listen({ port: 8000 });
% deno run --allow-net --allow-read main.ts
Listening at http://localhost:8000/
Use ctrl+c to stop
Requests to http://localhost:8000/ will respond with the index.html file above, and all other routes will respond with a 404 Not Found response.

Next js in subfolder /blog change index.js file for example to _blog_index.js?

in subfolder /blog can i change index.js file for example to _blog_index.js and it will be read as index.js?
each subfolder has index.js file and sometime is difficult to read in code editor, when i have many subfolders and many tabs open.
Thank u
This is possible when using rewrites() in next.config.js:
const nextConfig = {
async rewrites() {
return [
{
source: "/blog",
destination: "/blog/_blog_index",
},
];
},
};
module.exports = nextConfig;
However, keep in mind that rewrites() won't be supported if you're planning to export your app to static HTML because it requires a Node.js server.

Alerts in bootstrap & pug

I would like to know whether i have understood the workings of connect-flash/bootstrap/sessions. I do see the flash messages appear as expected. My question is to do with the colors related to the 'success' and 'danger'. While the messages appear as expected i am not seeing the associated colors,
Below are bits of package.json,
{
"dependencies": {
"body-parser": "^1.18.3",
"bootstrap": "^4.1.3",
"connect-flash": "^0.1.1",
"cookie-parser": "^1.4.3",
"express": "^4.16.4",
"express-messages": "^1.0.1",
"express-session": "^1.15.6",
"express-validator": "^5.3.0",
"mongoose": "^5.3.15",
"pug": "^2.0.3"
},
"devDependencies": {
"nodemon": "^1.18.7"
}
}
In my app.js,
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
// express session middleware
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}));
// express messages middleware
app.use(require('connect-flash')());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use(flash());
// my routes
let quotes = require('./routes/quotes');
let subscribers = require('./routes/subscribers');
app.use('/quotes', quotes);
app.use('/subscribers', subscribers);
// In my subscribers route,
router.post('/subscribe', function (req, res)
{
// logic to save to my database here
req.flash('success', 'Subscription confirmed.');
res.redirect('back');
});
In my services.pug file i have,
link(rel='stylesheet', href='/css/style.css')
link(rel='stylesheet' href='/node_modules/bootstrap/dist/css/bootstrap.css')
// other code in here
.container
h1 Subscribe to our newsletter
//- include subscribe.pug
form(method='POST', action= '/subscribe')
input(name = 'email',type='email', placeholder='Enter email')
button.button1(type='submit') Subscribe
!= messages('message',locals)
// at the bottom
script(src='/node_modules/jquery/dist/jquery.js')
script(src='/node_modules/bootstrap/dist/js/bootstrap.js')
In my message.pug i have,
.messages
each type in Object.keys(messages)
each message in messages[type]
div(class = "alert alert-"+ type) #{message}
Like i mentioned above the messages appear as expected. But i do not see the green color associated with success and the red for danger as i have seen in a tutorial i followed. I just see the message blended with the background color of the page. I would like to know what i am missing.
UPDATE
On checking the console on chrome i found the attached error messages. I have included the directory structure of the project as well. The bootstrap.css and jquery.js are not being found by the app.
This is where i set my public folder in app.js,
// set public folder
app.use(express.static(path.join(__dirname, 'public')));
The node_modules folder is available as well.
Thank you
You also need to serve bootstrap and jquery dist folders beside the public one:
// set public folder
app.use(express.static(path.join(__dirname, 'public')));
// serve bootstrap and jquery
app.use(express.static(path.join(__dirname, 'node_modules', 'bootstrap', 'dist')));
app.use(express.static(path.join(__dirname, 'node_modules', 'jquery', 'dist')));
and use them ( make sure styles are in head tag ):
link(rel='stylesheet' href='/css/bootstrap.css')
link(rel='stylesheet' href='/css/style.css')
and:
script(src='jquery.js')
script(src='/js/bootstrap.js')
of course in production you should use minified versions ( i.e: bootstrap.min.js ) or simply a CDN ( or both: when CDN is not available fall back to local ones )

Not link css file with ejs

I am working with simple express node js But my main.css file does not link with header.ejs both are the same folder shown in below picture.
I have searched on google but the problem still there.
my app.js file code
var express = require("express")
var app = express()
var request = require("request");
app.set("view engine", "ejs");
app.get("/", function(req, res){
res.render("search");
});
app.get("/results", function(req, res){
var url ="http://www.omdbapi.com/?s="+req.query.search+"&apikey=my_api_key"
request(url, function(error, response, body){
if(!error && response.statusCode == 200){
var data = JSON.parse(body)
// res.send(results["Search"]);
res.render("results",{data: data});
}
})
});
app.listen(5000,"localhost",function(){
console.log("movie search");
})
You have a wrong setup, Your view folder should only contain view files (in your case *.ejs files) but not static content.
Create another folder with name 'public' at root of your node project and move your main.css there and add the following code to serve static content.
app.use(express.static(__dirname + '/public'));
After this you should be able to access your main.css using localhost:5000/main.css If you see your content, The css import in your view file will start working.

Can't load CSS file (error in console log) on "localhost:3000/" in node.js?

re]5]5app.js file:
const express = require('express'),
app = express();
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'jade');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('index')
});
app.listen(3000);
console.log('listening on port 3000');
index.jade file:
doctype
html
head
title Home
link(rel='stylesheet', href='css/style.css')
body
header
h1 Home
footer
p Designed By Me
When I load the browser at localhost:3000/, I get 404, failed to load "localhost:3000/css/style.css". Whats the problem???
directory structure:
root
public
css
style.css
app.js
views
index.jade
THNX

Resources