nodejs express css and js not loaded - node.js

I use express on nodejs. The html-file I load doesn't get java-scripts and css-files.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h1>Hello, world!</h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script type="" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.js"></script>
</body>
</html>
This is my express-part in nodejs:
app.get('/', function(req, res){
console.log(req.path);
fs.readFile('mongo_client/index.html',function (err, data){
if(!err)
{
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
}
else
{
res.writeHead(400, {'Content-Type': 'text/html'});
res.end("index.html not found");
}
});
});
The only console.log is "/" once. The css and js file isn't even requested.
Edit:
I used the static middleware but it doesn't work either:
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
fs.readFile('mongo_client/index.html',function (err, data){
if(!err)
{
res.send(data);;
}
else
{
res.send("index.html not found");
}
});
});
Therefore I put my js and css - data to the public - folder.
Everytime I try to connect I download the index.html file.
Does anyone have a working example for a simple webserver using express? Do I have to use the file-reader ... I think there's another way using express-middleware.
I just need a simple example of an express web-server that is supporting css and js ... I can't find anything that's just that basic.

app.get('/') will only respond to requests at the root, not anything beyond that. Your css and other assets are at /css/bootstrap.min.css which your route doesn't handle.
But for express, use the static middleware to do all that for you. http://expressjs.com/api.html#middleware
This article also explains the setup http://blog.modulus.io/nodejs-and-express-static-content
Update: a sample app
Express is capable of generating a sample app that supports static, with optional support for CSS pre-processors. Read their guide: http://expressjs.com/guide.html but the basic steps are to install express globally
npm install -g express
Then use the command line to generate the skeleton of your app
express --css stylus myapp
The above provides support for Stylus. You can specify less if you prefer. Or to generate it with support for basic css files
express myapp
Then cd into myapp, or whatever name you provided, and you can see how it's done.

Related

Why my browser shows blank page when I run express server (React.js)?

I'm new to React. I want to deploy my react project to Heroku. To do that I implemented a simple express server. But nothing renders on my browser at localhost:3000 when I run the server with node server/server.js. Am I missing something obvious here?
My project structure:
server.js:
const path = require('path');
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));
// create a GET route
app.get('/*', (req, res) => {
res.send(res.sendFile(path.join(__dirname, '../src/index.html')));
});
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
There is no index.html in src. With create-react-app the file index.html it would be put into build when command npm run build is executed. It generates an index.html with urls to the JS/CSS dynamically injected. One option is you you could consider putting the React application into public, then target index.html of the build folder generated by npm run build:
// create a GET route
app.get('/*', (req, res) => {
// update this path to match how you set up express to serve static and where your build is output to
res.send(res.sendFile(path.join(__dirname, 'public', 'path', 'to', 'build', 'index.html')));
});
Also you need to make sure you have static file serving set up for express:
app.use(express.static('public'))
static can also target multiple directories in case you don't want to nest your react project too deeply:
app.use(express.static('public'))
app.use(express.static('build'))
It's fairly common to have static assets in public such as images, but regardless of the structure you choose, you need to specify a path for static assets including the HTML, CSS, and JS generated by create-react-app build.

Serving React build with Express shows nothing

I have this project structure:
app
server.js
frontend
build
index.html
build directory is the result after npm run build in my React app (created with create-react-app). There are more files but I omit them for the example.
I want to serve the React app as static files, so in server.js, I have this:
app.use(express.static(path.resolve(__dirname, 'frontend/build')));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'frontend/build', 'index.html'));
});
app.listen(9001);
I navigate to http://localhost:9001 in my browser and there are no errors but the screen is blank. React app is not shown.
If I run the React app (from inside frontend directory) with npm start, it works properly (in default webpack port 3000).
This is the build/index.html file (pretty printed):
<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
<meta name="theme-color" content="#000000"><link rel="manifest" href="/manifest.json">
<link rel="shortcut icon" href="/favicon.ico">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"/>
<title>React App</title><link href="/static/css/main.65027555.css" rel="stylesheet"></head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="text/javascript" src="/static/js/main.a4d4d402.js"></script>
</body>
</html>
If I navigate to http://localhost:9001/static/js/main.a4d4d402.js, I can see the javascript file.
I found the error. There was an error in the bootstrap imports in index.html. I was closing a tag twice. In my question looks well because I have pretty printed by hand and maybe I have corrected it somehow.

Node express server not serving images folder

When I run my bundled React app on the production server, it can't find my image files and I'm not sure why. I'm fairly sure it's got something to do with my node express configuration and/or my .ejs template file.
server.js
var express = require('express')
var app = express();
const path = require('path');
app.use('/static', express.static(__dirname + '/static'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('*', function (req, res) {
res.render("index");
});
const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || 'production';
app.listen(port, err => {
if (err) {
return console.error(err);
}
console.info(`Server running on http://localhost:${port} [${env}]`);
});
index.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Production Server</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=BenchNine" rel="stylesheet">
<link rel="stylesheet" href="../static/css/main.css">
</head>
<body>
<div id="root"></div>
<script src="../static/js/bundle.js"></script>
</body>
</html>
My CSS stylesheet is called in the template file, and all JS is bundled into bundle.js which is referenced in the script tag. I'm not sure how to get my application to recognise the /img folder though, as at the moment it doesn't.
Here's my file structure:
- static
- css
- main.css
- js
- bundle.js
- img (contains all image files)
When I run the app however, and I open 'Sources' in Chrome console, the /img file is not being served.
I thought this line indicates that express serves everything in the /static folder...
app.use('/static', express.static(__dirname + '/static'));
...yet only two out of three files are being served.
Would massively appreciate if anyone can tell me where I'm going wrong with my setup.
Thanks in advance.
The source tab in the DevTools will only show the contents that are being used by the browser in your case index.ejs, it's only using .js and .css files
in Index.ejs you are loading
<script src="../static/js/bundle.js"></script> and <link rel="stylesheet" href="../static/css/main.css">
so that means the middleware app.use('/static', express.static(__dirname + '/static')); will check whether or not the /js/bundle.js and /css/main.css are there in the static folder, if yes it will serve them, if not then will give file or folder not found.
That means whatever you will load from the static folder in index.ejs or use in index.ejs only that contents and files will be present in the source tab.
Try adding a image in index.ejs from static folder and then view the source tab
or remove <script src="../static/js/bundle.js"></script> and view source tab you won't see JS folder as it's not been used by index.ejs
Always reload the server

I can't use EJS layout using res.render()

I've been trying to use express-ejs-layouts module.
My when I try second route, browser finds my JS and CSS resource file under my second EJS files -that was written by me into second route function.
What should I do?
My Layout appears properly with my first route process like the following.
my first route;
app.get('/', function(req, res) {
res.render('home/index');
});
my layout.ejs file;
<!DOCTYPE html>
<html lang="tr">
<head>
<link rel="stylesheet" href="bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<% include navbar %>
<%- body %>
<script src="js/jquery.js"></script>
<script src="bootstrap/js/bootstrap.js"></script>
</body>
</html>
So far everything is good. My resource files (css and js) linked and I can see my home/index.ejs properly. And then I try my second route like the following;
my second route;
app.get('/user/:id', function(req, res) {
res.render('user/index');
});
My browser console gives the below errors;
Failed to load resource: the server responded with a status of 404
(Not Found) http://localhost:1337/user/bootstrap/css/bootstrap.css
Failed to load resource: the server responded with a status of 404
(Not Found) http://localhost:1337/user/css/styles.css
Failed to load resource: the server responded with a status of 404
(Not Found) http://localhost:1337/user/js/jquery.js
Failed to load resource: the server responded with a status of 404
(Not Found) http://localhost:1337/user/bootstrap/js/bootstrap.js
Express needs a 'public' named folder to check resources. So I've put my resources files into a ".../public/" folder, rewrote src link and I got succeed.
I've defined a new static path;
app.use(express.static(__dirname + '/public'));
An then I changed my new layout.ejs file like the below;
<!DOCTYPE html>
<html lang="tr">
<head>
<link rel="stylesheet" href="/css/bootstrap.css">
<link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<% include navbar %>
<%- body %>
<script src="/js/jquery.js"></script>
<script src="/js/bootstrap.js"></script>
</body>
</html>

Getting TypeError: App.Router is undefined after building ember.js

Posting here as requested original post can be found here
Hello, I would like to build ember.js using Ubuntu 13.
I have cloned the official Github project, cd into the project and as described in the readme file I did:
bundle install
rake dist
no error is shown on screen and as a result I get a directory shown in the image
I would like to use ember and ember-data, so I include
ember.js
ember-data-deps.js
files in my test project.
The problem is that I am getting a TypeError: App.Router is undefined
I am using this at my client.js file to init ember
this.App = Ember.Application.create();
App.Router.map(function() {
this.route('contributors');
this.route('contributor', {path: '/contributors/:contributor_id'});
});
Am I doing something wrong in the build process?
Should I include some other js files in my project?
Thank you in advanced.
The TypeError: App.Router is undefined error is because ember.js is not loaded correctly or in the correct order.
To get ember-data (that is separate from ember.js) you have to clone this repo (https://github.com/emberjs/data) and follow the build instructions in the readme file, it's straight forward, and once you have the dist directory from the ember-data build process get the file ember-data.js development version or ember-data.min.js for production (well, production... ember-data is still considered unstable for production environments).
here is a simple ember project setup using ember-data:
index.html
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>ember app</title>
</head>
<body>
<script type="text/x-handlebars">
hello world!
</script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="http://builds.emberjs.com.s3.amazonaws.com/handlebars-1.0.0-rc.3.js"></script>
<script type="text/javascript" src="http://builds.emberjs.com.s3.amazonaws.com/ember-latest.js"></script>
<script type="text/javascript" src="http://builds.emberjs.com.s3.amazonaws.com/ember-data-latest.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
app.js
var App = Ember.Application.create({
ready: function () {
console.log("app started...");
}
});
hope it helps

Resources