Having a issue figuring out how to navigate between EJS pages effectively:
File directory:
I want to go from my index.ejs page to the about.ejs page. This is the code for my index.ejs page which is currently not navigating properly:
index.ejs:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1> This is a link to about page</h1>
</body>
</html>
app.js server:
const express = require("express");
const path = require('path');
const app = express();
app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "ejs")
app.get("/", (req, res) => {
res.render("index")
});
app.use(express.static('public'));
app.listen(3000);
What could I enter in the href to properly reference the dynamic about.ejs file?
I already know that I can reference static files from my public folder but I want to refernce the dynamic ejs folder. If not possible any solution which provides the same functionality will also do.
You should render about.ejs template to use it on the client. To do that, you need to create a new route:
app.get("/about", (req, res) => {
res.render("about");
});
To open it use /about path.
Your link should point to /about.
Then you have to options. 1) have a function in your server to serve that page. 2) serve your pages dynamically.
1.
app.get("/about", (req, res) => {
res.render("about")
});
2.
app.get("/:page", (req, res) => {
res.render(req.params.page);
});
You need to create a route for your about page
app.get("/about", (req, res) => {
res.render("about")
});
And remove the extension from the hyperlink. The hyperlink should be :
About
Notice the correction in your index.ejs at line 7
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1><a href='/about'> About</a></h1> //there's no point including the ".ejs" extension at the end of the "about"
</body>
</html>
In your app.js server, also notice the addition of the (about route).
const express = require("express");
const path = require('path');
const app = express();
app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "ejs")
app.get("/", (req, res) => {
res.render("index")
});
app.get('/about', (req, res)=>{ //here you can include a new "about" route that should take you to the "about" page
res.render('about')
});
app.use(express.static('public'));
app.listen(3000);
Related
I have a basic website and am running into a problem. I am extremely new to this and can not seem to fix it.
When I run the server and browse to http://localhost:3000/class/create everything works fine. However, when I try to add a student I receive a message on the browser that says
" Cannot POST /api/create " and a 404 error in the console.
What is supposed to happen: The console logs "creating a student entry"
index.js
const express = require('express')
const app = express()
// loading body-parser
const bodyParser = require('body-parser')
// loading our routers
const mainRouter = require('./mainRoutes.js')
const classRouter = require('./classRoutes.js')
// tell Express to use bodyParser for JSON and URL encoded form bodies
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
// mounting the routers
app.use('/', mainRouter)
app.use('/class', classRouter)
app.listen(3000)
console.log('Express server running on port 3000')
classRoutes.js
const path = require('path')
const express = require('express')
const router = express.Router()
const classList = [] // our class list array
router.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'views', 'class', 'index.html'))
})
router.get('/create', function (req, res) {
res.sendFile(path.join(__dirname, 'views', 'class', 'create.html'))
})
// RESTful api
router.get('/api/list', function (req, res) {
res.json(classList) // Respond with JSON
})
router.get('/api/get/:id', function (req, res) {
res.json(classList[req.params.id]) // Notice the wildcard in the URL?
// Try browsing to /api/get/0 once you've added some entries
})
router.post('/api/create', function (req, res) {
console.log('creating a student entry')
})
module.exports = router
create.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Class List: Create</title>
<meta charset="utf-8" />
</head>
<body>
<form action="/api/create" method="post">
<div>
<label for="studentName">Enter The Student's Name:</label>
<input type="text" id="student" name="student">
</div>
<div class="button">
<button type="submit">Add</button>
</div>
</form>
</body>
</html>
Chrome Dev Tools output (network tab)
because you set app.use('/class', classRouter); /class must precede /api/create so the correct route is/class/api/create
use the correct absolute path: action="/class/api/create"
I'm using node.js, express, and ejs as a development environment. I've run into an issue where my main page isn't rendered. However, other pages are rendered. I get absolutely no return when I access http://127.0.0.1:9999. However, I get the proper response when I access http://127.0.0.1:9999/about. I replaced my normal page with a very simple test page to check if there was something wrong it. Nope. No change. I can only conclude that the path '/' (or '') isn't seeing the request.
Can anyone see the problem? Thanks
app.js
const path = require("path");
const express = require("express");
const ejs = require("ejs");
const app = express();
const port = 9999;
const viewsPath = path.join(__dirname, "./views");
app.set("view engine", "ejs");
app.set("views", viewsPath);
app.use(express.static(path.join(__dirname, "/public")));
app.get("/", function(req, res) {
console.log("index accessed");
res.status(200).render("partials/test.ejs");
});
app.get("/about", function(req, res) {
console.log("about accessed");
res.status(200).render("partials/test.ejs");
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
test.ejs
<h1>This is a test page</h1>
I added the following route, and the path is not matched.
app.get("*", function(req, res) {
console.log("* accessed");
res.status(200).render("partials/test.ejs");
});
In the meanwhile it is possible to use:
app.use(express.static(app_path, {
index: false
}));
Credits to
When i go to posts index route (http://localhost:3000/posts), the main.js file served in /public/scripts folder is found, but when i go to the posts show route (...localhost:3000/posts/:id) or any other posts route, chrome's console throws an 404 error for main.js file. Apparently, it's trying to find /scripts at the /views/posts directory.
http://imgur.com/2uNAgBw
Here's my code
app.js:
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
methodOverride = require("method-override");
var postRoutes = require("./routes/posts");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(methodOverride("_method"));
app.use("/posts",postRoutes);
app.listen(3000, function(){
console.log("application server is running")
});
routes/posts.js
var Post = require("../models/post");
var express = require("express");
var router = express.Router();
var middleware = require("../middleware");
//INDEX - show all colectives
router.get("/", function(req, res){
console.log("get request at /posts");
Post.find({}, function(err, allPosts){
if(err){
console.log(err);
} else {
res.render("posts/index", {posts: allPosts});
} //if
}); // Post.find
}); //router.get
//NEW - show form for creating new post
router.get("/new", middleware.isLoggedIn, function(req, res){
console.log("get request at /posts/new");
res.render("posts/new");
}); //router.get
//SHOW - show more info about a post
router.get("/:id", function(req, res){
console.log("get request at /posts/" + req.params.id);
//find the post with provided id
Post.findById(req.params.id).populate("comments").exec(function(err, foundPost){
if(err){
console.log(err);
} else {
res.render("posts/show", {post: foundPost});
} // if
}); //Post.findByID
}); //router.get
//EDIT - show edit post view
router.get("/:id/edit", middleware.checkPostOwnership, function(req, res){
console.log("get request at /posts/" + req.params.id + "/edit");
Post.findById(req.params.id, function(err, foundPost){
res.render("posts/edit", {post: foundPost});
}); //Post.findById
}); //router.get
module.exports = router;
views/posts/show.ejs
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<div id="masterContainer">
<div class="container">
...
</div>
</div>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<!-- Bootstrap's JavaScript-->
<script type="text/javascript" src="http://ricostacruz.com/jquery.transit/jquery.transit.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="scripts/main.js"></script>
</body>
</html>
Sorry if i misused some programming terms, i'm new to web developing and not a native english speaker. Thanks ahead.
Add a / to the front of the src of your script tag.
<script src="/scripts/main.js"></script>
This way, that script tag always requests the same URL, no matter which page it's on. If you omit the leading /, the actual URL requested is relative to the current URL. For example, if you're currently at localhost:3000/foo/bar, that script tag without the leading / would send a request to /foo/scripts/main.js.
I would add a static express middleware to app.js to avoid problems like that.
app.use('/scripts', express.static(_dirname + '/path/to/scripts'));
Basically, what that does is make sure that whichever level you are on your app, express will always know where to look for the folder scripts.
You should to check the availability of the file "script/main.js".
Look to views/posts/show.ejs:
<script src="scripts/main.js"></script>
It looks like the server-side code works, but browser can't load this file on the path relative to the current route.
I'm using the following node.js/express.js server,
index.js:
const express = require('express');
const path = require('path');
const app = express();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8000, function () {
console.log('Listening on port: 8000!');
});
and the following html file,
index.html:
<!doctype html>
<html>
<head>
<title>Will Alley</title>
</head>
<body>
<style type="text/css">
img {
width: 100%;
height: 100%;
}
</style>
<h2 id="myName">Will Alley</h2>
<img src="./DSC_1546_700_464.jpg" alt="an image.">
</body>
</html>
all my files (index.js, index.html, DSC_1546_700_464.jpg) are in the same directory.
when I start my server and navigate to "localhost:8000" all that is displayed is the heading, and the images alt text.
Any help is greatly appreciated.
You have only one route in express, the one for '/'.
Below are two additions, one that answers your specific question by adding app.use(express.static(__dirname)) which is dangerous. The safer way is to use something like app.use('/images',express.static(__dirname+'/images')) to serve just certain subdirectories where you put servable stuff.
const express = require('express');
const path = require('path');
const app = express();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
// Static route for files in the current directory...
// Note that this serves all files relative to the given
// path, even ones you probably don't want.
app.use(express.static(__dirname));
// Note: you should really put these files in a subdirectory
// And use static like this:
app.use('/images', express.static(__dirname +'/images'));
app.listen(8000, function () {
console.log('Listening on port: 8000!');
});
I am really new to the whole MEAN-stack and are trying to create an application on openshift but are unable to render a new page.
I just keep getting this error and can't solve it with anything I've googled.
My Error: Failed to lookup view "/register" in public directory
It works completely fine to render the index page with app.get('/', func()) in server.js and tried to to the exact same thing with app.get('/register). I used to have the same problem with '/' at first but solved it using app.use(express.static(__dirname + '/public'));
Both index.html and register.html are located in the public directory.
These are extracts of my code:
index.html
<body ng-app="">
<div class="container" ng-controller="LoginController" >
<h1>Logg in</h1>
<input class="form-control" placeholder="ID"/>
<input class="form-control" placeholder="Password"/>
<button class="btn">Logga in</button>
<button ng-click="open()" class="btn">Register User</button>
</div>
</body>
logincontroller
function LoginController($scope, $http) {
console.log("Hello from Login");
$scope.open = function () {
console.log('open i login.js');
$http.get('/register')
};
};
server.js
var express = require('express');
var fs = require('fs');
var mongojs = require('mongojs');
var jade = require('jade')
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.get('/env',function(req, res){
res.json(process.env);
});
app.get('/', function (req, res) {
res.render('/index', {});
});
app.get('/register', function (req, res) {
res.render('/register');
});
app.set('view engine', 'jade');
There are a couple of issues.
1) Don't use a slash for the 'register' file. This is a file in the /public folder, not a folder or route.
app.get('/register', function (req, res) {
res.render('register');
});
2) You have set jade as your rendering engine. This means you will be serving .jade files. Your public folder should have index.jade. And it should look like this:
html
body(ng-app='')
.container(ng-controller='LoginController')
h1 Logg in
input.form-control(placeholder='ID')
input.form-control(placeholder='Password')
button.btn Logga in
button.btn(ng-click='open()') Register User
A couple of notes:
Jade is a HTML templating engine, it's relatively straight forward, see http://jade-lang.com/tutorial/.
There is express-generator which will give you an example app, it's an excellent starting point: http://expressjs.com/en/starter/generator.html
By the way, there is also an HTML-2-Jade converter, I find this helpful sometimes: http://html2jade.org/