I'm trying to use the login templates (Took from: 50 Free HTML5 And CSS3 Login Forms For Your Website 201
My directory set up is like this :
-css
|
-- style.css
- js
|
-- index.js
|
index.html
The head of the index.html file looks:
<head>
<meta charset="UTF-8">
<title>Sign-Up/Login Form</title>
<link href='http://fonts.googleapis.com/css?family=Titillium+Web:400,300,600' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
and the body contains the includes scrips:
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
My node.js looks:
// Import Required Module
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
// css
var path = require('path')
app.use(express.static(path.join(__dirname, 'public')));
// Create instances
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Get
app.get('/', function (req, res) {
console.log('Get: /');
res.sendFile('LoginTemplate/index.html', {root: __dirname })
})
/*
app.get('css/style.css', function (req, res) {
console.log('Get: css/style.css');
res.sendFile('css/style.css', {root: __dirname })
})
*/
// Listner
app.listen(3001, function () {
console.log('Example app listening on port 3001!')
})
When loading the html file I'm getting the error:
GET http://127.0.0.1:3001/css/style.css
I have tried to look for solution at:
Can not get CSS file
And created the public folder and copy the css folder inside, but it still doesnt work.
How can I load the css & js files ?
// Import Required Module
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
// Create instances
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Get
app.get('/', function (req, res) {
console.log('Get: /');
res.sendFile('LoginTemplate/index.html', {root: __dirname })
})
app.get('/css/style.css', function (req, res) {
console.log('Get: css/style.css');
res.sendFile('LoginTemplate/css/style.css', {root: __dirname })
})
app.get('/js/index.js', function (req, res) {
console.log('Get: js/index.js');
res.sendFile('LoginTemplate/js/index.js', {root: __dirname })
})
// Listner
app.listen(3001, function () {
console.log('Example app listening on port 3001!')
})
Everything looks good in your code and folder setup. From the URL you are posting (http://127.0.0.1:3001/css/style.css), I am guessing that the error lies in your server instance. Check the definition files and make sure that the server has permission to read css/style.css.
I have run into this problem when the file and folder do not have the right permissions. A quick check for this is running something similar to sudo chmod -R 0777 [path_to_your_project] (linux and Mac systems will use this command). This command gives full access to all users and guests to read, write and execute your files and is a quick way to verify whether the problem is user rights.
I have also run into this same problem when my web server is not correctly configured. In those cases, I had accidentally allowed the web server to share all files in the root folder (eg: /var/www ), but not any sub folders, so (using the example) the folder /var/www/images would be parsed by the web server and seen as an area that is protected. In this case, the Web Server has access, but it refuses to serve the files based on the configuration rules.
I hope one of these two fixes helps direct you down the right path to a solution.
Good luck!
Related
So, this is a strange one. I am running a Nodejs application using Express and Pug. I have all my static files in a Public folder and my Pug files in the Views folder. I set up the app.js file to grab all the static files from the Public folder. I am using Nginx to handle the server.
Here is the weird part, when i run it on a Ubuntu instance using AWS I get a 404 on all of my js and css files. When i run it on my local computer I get 304 errors, but everything loads and works.
Any ideas what I did wrong? I will Show some of my code beneath.
Pug File
doctype html
html
head
meta(charset='utf-8')
title Signature Pad
meta(name='description', content='Signature Pad - HTML5 canvas based smooth signature drawing using variable width spline interpolation.')
meta(name='viewport', content='width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no')
meta(name='apple-mobile-web-app-capable', content='yes')
meta(name='apple-mobile-web-app-status-bar-style', content='black')
link(rel='stylesheet', href='stylesheets/signature-pad.css')
#signature-pad.signature-pad
.signature-pad--body
canvas
.signature-pad--footer
div
.description Sign Above
.signature-pad--actions
div
button.button.clear(type='button', data-action='clear') Clear
button.button(type='button', data-action='undo') Undo
div
form(action='', method='POST', onsubmit='completeAndRedirect();return false;')
label(for='fname') First name:
input#firstName(type='text', name='fname')
label(for='lname') Last name:
input#lastName(type='text', name='lname')
br
br
label(for='company') Company:
input#company(type='text', name='company')
br
br
input.button.save(type='submit', value='Submit', data-action='save-svg')
script(src='js/signature_pad.umd.js')
script(src='js/app.js')
App.js file
const express = require('express');
const path = require('path');
const NetSuiteOauth = require('netsuite-tba-oauth');
const bodyParser = require('body-parser');
const app = express();
//Parse incoming request
app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: false }));
//View engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
//Static Files
app.use(express.static(__dirname + '/Public'));
app.get('/', (req, res, next)=> {
return res.render('landing', {title: 'Home'})
});
app.get('/customer', (req, res, next)=> {
return res.render('signature', {title: 'Customer'})
});
app.get('/employee', (req, res, next)=> {
return res.render('signature', {title: 'Employee'})
});
app.post('/customer', (req, res, next)=>{
return res.render('entered', {title: 'Home'})
});
app.post('/employee', (req, res, next)=>{
return res.render('entered', {title: 'Home'})
});
app.listen(8080);
Folder Structure
Image of File Structure
Please let me know if I am not clear, first time posing on Stack
On nginx in your production server, you need to modify the sites_available file, to point to your static folder as default.
server {
root /www/data;
location / {
}
.....
}
please check attached link for serving static folder static nginx
I am relatively new to using Node and am trying to make a simple HTML page that can get images, stylesheets, and scripts locally. Every time I try to load a local file, it returns a 404 status. I have tried multiple solutions from StackOverflow and other sources and still cannot get this to work.
Here is my code in app.js:
const app = require('express')();
const http = require('http').createServer(app);
var portNumber = 8085;
app.get('/', function(reg, res) {
res.sendFile(__dirname + '/index.html');
});
http.listen(portNumber, function() {
console.log('Listening on port ' + portNumber);
});
I have a CSS file at public > stylesheets > style.css linked to my HTML document.
<link rel="stylesheet" type="text/css" href="public/stylesheets/style.css" />
I get a 404 error in my browser's console. I also get a MIME error:
The resource from “http://localhost:8085/public/stylesheets/style.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
Any local images I try to load also give a 404 error.
I have tried adding app.use(express.static('public')); to make the public folder the root to serve static content as shown in the Express documentation, but I still got 404 errors.
const express = require('express');
const app = express();
const http = require('http').createServer(app);
var portNumber = 8085;
app.use(express.static('public'));
app.get('/', function(reg, res) {
res.sendFile(__dirname + '/index.html');
});
http.listen(portNumber, function() {
console.log('Listening on port ' + portNumber);
});
I am not sure what I am supposed to do. All I want is to be able to load local files in my HTML document. How do I get these files to be displayed publicly instead of giving a 404 error?
The reason for the mime error is actually confusing - it's due to the browser not being able to find that file.
Remove the /public part of the path location as that is the folder so it's being served from:
<link rel="stylesheet" type="text/css" href="/stylesheets/style.css" />
Same for all your other static files: /assets/mypic.png etc
Update your location for the static path as follows:
app.use(express.static(path.join(__dirname, 'public'), {index: false}));
Then, update sendFile to use and absolute path as follows:
return res.sendfile(path.resolve('./index.html'));
// or
return res.sendfile(path.join(__dirname, 'index.html'));
You should try using
app.use(express.static(__dirname + "/public"));
That way express knows where to search for that public folder.
I built a react app using "react-scripts". The application runs perfectly on my local development server but when I deploy to my actual server the applications seems to not find the main JS and CSS files being compiled. I get 404 on both.
Following is the information that might help.
The files on the server are located at
ads/build/static/js and ads/build/static/css || respectively
The 404s I am getting are on the following files:
https://www.example.com/ads/build/static/css/main.41938fe2.css
https://www.example.com/ads/build/static/js/main.74995495.js
Here is how my server is configured:
const express = require('express');
const path = require('path');
const app = express();
const favicon = require('serve-favicon');
//favicon
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.get('/ads', function (req, res) {
app.use(express.static(path.join(__dirname, 'build/static')));
console.log(path.join(__dirname, 'build'));
res.sendFile(path.join(__dirname, '/build/index.html'));
});
app.listen(9000);
In my package.json I have also included the homepage parameter as:
"homepage" : "https://www.example.com/ads
UPDATE
When I run the app on the server itself with the following path:
dedicated-server-host:9000/static/js/main.74995495.js that renders the JS file correctly
Is there some configuration that I am missing, the routing doesn't seem to be working. Please advise.
Use some indentation so you will see error like this:
app.get('/ads', function (req, res) {
app.use(express.static(path.join(__dirname, 'build/static')));
console.log(path.join(__dirname, 'build'));
res.sendFile(path.join(__dirname, '/build/index.html'));
});
You are setting the static route inside of the /ads handler, will add a new express.static route handler on every GET /ads request.
This will set the static route on server startup:
app.use(express.static(path.join(__dirname, 'build/static')));
app.get('/ads', function (req, res) {
console.log(path.join(__dirname, 'build'));
res.sendFile(path.join(__dirname, '/build/index.html'));
});
or:
app.get('/ads', function (req, res) {
console.log(path.join(__dirname, 'build'));
res.sendFile(path.join(__dirname, '/build/index.html'));
});
app.use(express.static(path.join(__dirname, 'build/static')));
But make sure that you get the path right - for example you may need:
app.use('/ads/build/static', express.static(path.join(__dirname, 'build/static')));
if you want the URL in your question to work.
To make it much simpler, you could use just this single handler to make express.static handle both the css/js and index.html at the same time:
app.use('/ads', express.static(path.join(__dirname, 'build')));
and change your index.html to use:
https://www.example.com/ads/static/css/main.41938fe2.css
https://www.example.com/ads/static/js/main.74995495.js
instead of:
https://www.example.com/ads/build/static/css/main.41938fe2.css
https://www.example.com/ads/build/static/js/main.74995495.js
Sometimes getting your paths structure right in the first place can make your route handlers much easier.
I am very novice at Node.
I made the server run as follows (index.js):
var express = require('express'),
views = require('./routes/views');
var app = express();
// Get an instance of router
//var router = express.Router();
//app.use(express.static(__dirname+'/routes/keenIO/assets/css'));
app.use('/', views);
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
I use the router in this way, setting also the, I guess correct ones, paths to the static content (views.js):
var express = require('express');
var path = require("path");
var router = express.Router();
router.use('/assets', express.static(__dirname+'/keenIO/assets'));
router.use('/specificAssets', express.static(__dirname+'/keenIO/examples'));
//app.use(express.static(__dirname+'/routes/keenIO/assets/css'));
router.get('/', function(req, res) {
//res.send('GET handler for /views route.');
var indexPatch = path.join(__dirname+'/keenIO/examples/connected-devices/index.html');
res.sendFile(indexPatch);
//res.send(__dirname);
});
router.get('/rules', function(req, res) {
//res.send('GET handler for /views route.');
var indexPatch = path.join(__dirname+'/keenIO/examples/connected-devices/rules.html');
res.sendFile(indexPatch);
//res.send(__dirname);
});
router.get('/json', function(req, res) {
//res.send('POST handler for /views route.');
var fs = require('fs');
//res.send('HOLA MUNDO');
var obj;
fs.readFile('network-big.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
res.send(obj);
});
});
module.exports = router;
So, In the .html file I use for example this to reach to the css, and similar to reach to the javascript files:
<link rel="stylesheet" type="text/css" href="assets/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="assets/css/keen-dashboards.css" />
<link rel="stylesheet" type="text/css" href="specificAssets/connected-devices/connected-devices.css" />
I start this and everything is fine, but as I try to load the same index.html for example clicking on a link ( with the path to it: specificAssets/connected-devices/index.html) it has no style at all.
EDITED 25/10/16 3:30 p.m:
Well, inspecting the element with Chrome, as I click on the links I get doubled one part of the patch, getting for some static resources http://localhost:3000/assets/assets/resource.{css/js}
But it appropriately loaded the first time I access to the .html with http://localhost:3000. I am confused...
Any advise will be very appreciated.
Best regards,
Iván
Create a proper structure and keep all your html files in a views folder and do it following way that will work for you And for styling just keep your css in html file only or keep them in same folder and require file in html Easiest way to do is to keep your html and style in same file
router.set('views', path.join(__dirname, 'views'));
router.get('/', function(req, res) {
res.render('index');
});
If you want to use a proper structure then you need to know this thing as well
Since .css files are static files you have to serve them to the clients. However, you do not serve static files as a express middleware. Add the following middleware to your express app and move the css folder under the public directory (you should create a public directory)
app.use(express.static(path.join(__dirname, 'public')));
I use this function to send html file to client, but in client I get nothing (blank page) without error. Something I wrong?, please help?
var express = require('express');
var fs = require('fs');
var app = express();
app.set('view engine', 'jade');
app.engine('jade', require('jade').__express);
app.get('/test', function(req, res) {
fs.readFile(__dirname + '/views/test.html', 'utf8', function(err, text){
res.send(text);
});
var port = process.env.PORT || 80;
var server = app.listen(port);
console.log('Express app started on port ' + port);
My test.html file
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style something here </style>
<title>Test</title>
<script src="..."></script>
</head>
<body>
<div> Somthing here </div>
<script type="text/javascript">
//something here
</script>
</body></html>
Try your code like this:
var app = express();
app.get('/test', function(req, res) {
res.sendFile('views/test.html', {root: __dirname })
});
Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.
You don't need the app.engine line, as that is handled internally by express.
you can render the page in express more easily
var app = require('express')();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.get('/signup',function(req,res){
res.sendFile(path.join(__dirname,'/signup.html'));
});
so if u request like http://127.0.0.1:8080/signup that it will render signup.html page under views folder.
After years, I want to add another approach by using a view engine in Express.js
var fs = require('fs');
app.get('/test', function(req, res, next) {
var html = fs.readFileSync('./html/test.html', 'utf8')
res.render('test', { html: html })
// or res.send(html)
})
Then, do that in your views/test if you choose res.render method at the above code (I'm writing in EJS format):
<%- locals.html %>
That's all.
In this way, you don't need to break your View Engine arrangements.
The "../" is considered malicious and will result in ForbiddenError: Forbidden at SendStream.error... exception.
The way to go is using a path module:
var path = require('path');
res.sendFile(path.resolve('views/auth/success.html'));
var app = express();
app.get('/test', function(req, res) {
res.sendFile(__dirname + "/view/test.html")
});
Here __dirname, gives you the current path where your files are saved. So in res.sendFile(), we first tell our current location by __dirname + (then we locate the specific file which should we shown on the home page i. e ) "vies/test.html".
Follow this simple process and send html file ->
res.sendfile("views/home.html"); // don't use capitla latter F with sendFile you must be use small letter f
example : sendfile();