I'm very new to node, express etc. I've made a blog-app and i'm facing a problem. I'm using mongoose, node, express and ejs.
When i call
router.get('/posts', function(req, res){ Post.find({}, function(err, posts){
res.render('viewpost.ejs', {
posts
}); }); });
Everything works perfectly fine. I got my posts and css is working as well. The problem is when i call
router.get('/posts/:posts_id', function(req, res){
Post.find({_id: req.params.posts_id}, function(err, posts){
res.render('viewpost.ejs',{
posts
});
});
});
Post seems to be working but in console i got
GET /posts/posts.css 304 1.854 ms
And the viewpost.ejs looks like it's not using the css.
Server file server.js
app.use(express.static('public'))
app.use(express.static(path.join(__dirname, 'public/css/')));
app.use(express.static(path.join(__dirname, 'public/img/')));
viewpost.ejs
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.css"/>
<link rel="stylesheet" href="style.css">
<script src="/bower_components/jquery/dist/jquery.js"></script>
</head>
<body class="cyc">
<% include ./partials/navbar.ejs %>
<%= posts %>
</body>
</html>
So when i use route without req.params everything seems to be working
ok. When i call it with any param my css file is not working.
<link rel="stylesheet" href="style.css"> tries to load style.css from the same path where the HTML page is. So, for /posts, it will try loading /style.css and for /posts/1, it will try to load /posts/style.css. But the latter matches your /posts/:posts_id endpoint, so that gets called instead with posts_id == 'style.css', which is nonsensical.
The solution is quite simply to make the link absolute:
<link rel="stylesheet" href="/style.css">
I was facing the same issue,but finally I solved it.
Do Following:
In Your HTML or EJS File write:
<link rel="stylesheet" href="../style.css">
in head section,it will work for both /post and /post:id
Related
I'm working in a new web portal. So far using the express and node.js i have a server and some ejs files.
The body structure of my site is like this:
- node modules
- public
--javascript
---myScript.js
-views
--pages
---index.ejs
---about.ejs
--partials
---footer.ejs
---head.ejs
---header.ejs
package.json
server.js
server.js
var express = require('express');
var app = express();
app.set('view engine', 'ejs'); // set the view engine to ejs
app.get('/', function(req, res) {res.render('pages/index');}); // index page
app.get('/about', function(req, res) { res.render('pages/about');}); // about page
app.listen(8080);
console.log('Portal is listening to port 8080 ');
and the index.ejs
<html lang="en">
<head>
<% include ../partials/head %>
</head>
<body class="container">
<header>
<% include ../partials/header %>
</header>
<main>
<div class="jumbotron">
<h1>MyPortal</h1>
<button>Press</button>
<% var test = 101; %>
</div>
</main>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
In the partials i want to call and use an external .js file /public/javascript/myScript.js so i can use variable from it in my ejs page or send a variable.
my js file have a simple function (just to see if it's working) that print in console if the button (in index.ejs) is pressed.
myScript.js
$(function() {
$("button").on("click", function () {
console.log("button pressed");
});
});
I'm trying to call the external js in head.ejs (or in index.ejs)...
<!-- views/partials/head.ejs -->
<meta charset="UTF-8">
<title>MyPortal</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style>body { padding-top:50px; } </style>
<script type="text/javascript" src="/pubic/javascript/myScript.js"></script>
but i'm getting this error (in console)
Loading failed for the <script> with source “http://localhost:8080/pubic/javascript/myScript.js”.
Any idea why this happens and how to solve it?
Since you are trying to load client-side JavaScript, the fact you are using EJS is irrelevent. A standard HTML script element is all you need in the template, and you have that.
You do, however, need to provide a URL (with the src attribute) that the web browser can use to fetch the script … and your script has no URL.
You are getting the message Loading failed for the with source “http://localhost:8080/pubic/javascript/myScript.js”. because it is a 404 Error.
You should use the static module to provide the JS file with a URL.
app.use("/public", express.static('public'))
Add this to your server.js file,
app.use(express.static(__dirname + "/public");
And to link the js file with your ejs file,
I am trying to write a simple node.js based application which can use JustGage (JavaScript-based plugin). Following is my Node.js application.
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8080);
Following is the index.html page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Temperature Sensor</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="static/resources/js/justgage.js"></script>
<script type="text/javascript" src="static/resources/js/raphael-2.1.4.min.js"></script>
<script>
window.onload = function(){
var g = new JustGage({
id: "g_a411_faculty",
value: 22,
min: 10,
max: 40,
title: "A411 - Faculty Office",
label: "Celsius",
levelColors: [
"#ffffff",
"#f9c802",
"#FF0000"
]
});
};
</script>
</head>
<body>
<div id="g_a411_faculty" class="col-sm-6" style="width:400px; height:320px"></div>
</body>
</html>
When I run the code and open http://localhost:8080 in Google Chrome, the index page shows an error that JustGage is not defined (in Developer tools). However, when I simply open up index.html (without using Node.js) in Chrome, the page works fine. Can you please help where am I going wrong?
I tried to resolve the issue by installing justgage package by
npm install justgage
However, when I write
var jg = require('justgage');
This shows a Reference Error - the document is not defined. Please help!
node.js isn't serving your static folder.
The website works when running directly from the folder as you are able to access the relative path of static/... from the same location.
When you run via node.js, you are only serving index.html and not the related assets.
Some useful ways of serving static files/folders are discussed in this thread
I'm trying to learn HTML/CSS and AngularJS by making a single-page web app that will show time, weather, and other info. My goal is to be able to drag and drop these on the web page so that a user can arrange them as they see fit.
My first step is to show time, which I'm able to do (I got the code based on this code from another answer). However, it doesn't actually work on my own environment and I'm not sure if it's because my files are incorrectly linked. My directory structure looks something like this:
-- app
+ -- clock.js
-- node_modules
-- public (holds css and images)
index.html
(some other files)
As you can see in my code, I wrote <script src="app/clock.js"></script>, but when I check localhost:8080, instead of the time, I get {{ clock | date 'HH:mm:ss' }}. Is there something else I need to include in the html or js file to get Angular to start working?
var app = angular.module('test_app', []);
app.controller('updateClock', function($scope, $interval) {
var tick = function() {
$scope.clock = Date.now();
}
tick();
$interval(tick, 1000);
});
<!DOCTYPE html>
<html>
<head>
<title>TEST PAGE</title>
<link href="/css/style.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:300,400,500,700" type="text/css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
</head>
<body>
<div ng-app="test_app">
<div class="container">
<div ng-controller='updateClock'>
<p>{{ clock | date: 'HH:mm:ss'}}</p>
</div>
</div>
</div>
</body>
<script src="app/clock.js"></script>
</html>
Edited to add server code:
// server.js
// using express
var express = require('express');
var app = express();
var port = 8080;
// route the app
var router = require("./app/routes")
app.use("/", router);
// set static files (css, images, etc)
app.use(express.static(__dirname + '/public'))
// start the server
app.listen(port,function() {
console.log('Live at port ' + port);
});
I have a problem loading external files into my index.html. My stylesheet as well as my JS files do not show up at all (Error 404 - Not Found). My directory structure is as follows.
My index.html is:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Orders and Customers</title>
<link rel="stylesheet" type="text/css" href="./assets/css/stylesheet.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular-route.min.js"></script>
<script src="./../app/app.js" type="text/javascript"></script>
<script src="./../app/controllers/customer/CustomerController.js"></script>
<script src="./../app/controllers/order/OrderController.js"></script>
<script src="./../app/services/customer/CustomerService.js"></script>
<script src="./../app/services/order/OrderService.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
This is what Chrome shows:
My server.js is:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
require('./server/config/mongoose.js');
require('./server/config/routes.js')(app);
app.use(express.static(path.join(__dirname, './views')));
app.listen(8000, function() {
console.log('Listening on Port 8000');
})
Any help is greatly appreciated!
Try this
in server.js
var router = express.Router();
router.use(express.static(path.resolve(__dirname, "../app")));
in index.html
<script src="/app.js" type="text/javascript"></script>
<script src="/controllers/customer/CustomerController.js"></script>
<script src="/controllers/order/OrderController.js"></script>
<script src="/services/customer/CustomerService.js"></script>
<script src="/services/order/OrderService.js"></script>
Router is middle-ware for capture * path.
For example, /service/* matches all requests under service path.
so I changed your code as to handle all resources under "/app" folder. (eg: /app/app.js, etc)
path.resolve changes path from relative to absolute.
it means that you can add another current working directory.
path.resolve(__dirname, "../app") add "/app" from current working directory (views). it parsed from "views/../app" to "/app"
(Reference) Path.resolve
The relative paths
<script src="./../app/app.js" type="text/javascript"></script>
etc, are pointing to the wrong directory.
Use the Network tab in your browser developer tools, to check what exact requests are going out.
If the whole app directory is public (Which, in my opinion, should not be the case), "./../" will refer to the views directory.
Single . refers to the current directory, which in this case is, the one containing your index.html. Double .. refers to the directory above it, which here is views.
Rather than
<script src="./../app/app.js" type="text/javascript"></script>
Try using the full path:
<script src="/app/app.js" type="text/javascript"></script>
<script src="/app/controllers/order/OrderController.js"></script>
Try this
app.use(express.static(path.join(__dirname, 'views')));
and just use
<link rel="stylesheet" type="text/css" href="assets/css/stylesheet.css">
Thanks to SeongHyeon, I was able to figure out the solution to my problem. I really appreciate your guys' help. I'd like to elaborate more on this just for my own reference.
When declaring your static path in express, you don't need to reference anything relative to the file that you're trying to import from. Instead, you simply reference the file from the static path that you've declared.
When I render my .ejs file the href and the src attributes are not referencing my local files. I am using node.js and express.
Here is the relevant part of the .ejs template.
<head>
<title></title>
<link rel='stylesheet' href='../public/stylesheets/styles.css' />
<script src="../us-map-1.0.1/lib/raphael.js"></script>
<!-- <script src="scale.raphael.js"></script> -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
<script src="../us-map-1.0.1/color.jquery.js"></script>
<script src="../us-map-1.0.1/jquery.usmap.js"></script>
<script>
</head>
This is router that renders the template
router.get('/submit', function(req, res, next) {...});
And this is what a typical query looks like
http://localhost:3000/submit?leftHashtag=dog&rightHashtag=cat
Any help on why this is happening would be greatly appreciated.
The problem was that I wasn't defining my static content serving.
To fix this I added an app.use statement to my app.js file
app.use('/submit', express.static(__dirname + '/public'));
So now any routes that begin with /submit will use this directory local to the app
__dirname/public
With __dirname being the current directory the app.js file is located in
If you would like to know more this blog goes into more detail about what is happening
http://blog.modulus.io/nodejs-and-express-static-content