How can I combine a node.js website that its frontend is based on html with another node.js website that its frontend is based on jade template engine? I am using Express framework.
On the frontend there are four files: index.html, index2.html, chat1.html, chat2.html, which are located in the public folder. The blog website that I want to add to this website has only jade template engine, which are located in the views folder.
The index.html (which is in public folder) is the entry point to the home page of the website. When from index.html I refer to index3.jade, which is the Home page of the second app, i.e., blog jade app, Chrome browser states: "404 Not Found". However, I can go to the other two pages of the blog jade website, i.e., Add Post and Add Category. It is only the Home page of the blog jade app that is not being displayed.
So, I am not able to see only the Home page of the blog jade app, which starts at the root directory. Both the html app and the blog jade app start at the root directory. I was able to make the blog jade app to be displayed at the root directory, but then I could not see the html app, which also starts at the root directory.
Here is how I referred to each file from index.html front page:
`<li>gallery</li>`
`<li>chat</li>`
`<li>blog</li>`
Is there a way to have the home page of the blog jade app to be displayed at a directory other than the root directory?
Here is the related app.js code:
// Gallery HTML Code
var routes = require('./');
app.get('/public/index.html');
// Blog Code
var mongo = require('mongodb');
var db = require('monk')('localhost/nodeblog');
var routes = require('./');
var routes = require('./routes/index3');
var posts = require('./routes/posts');
var categories = require('./routes/categories');
var app = express();
app.locals.moment = require('moment');
app.locals.truncateText = function(text, length) {
var truncatedText = text.substring(0, length);
return truncatedText;
}
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.'),
root = namespace.shift(),
formParam = root;
while (namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
// Connect-Flash from Express-Messages
app.use(flash());
app.use(function(req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
// Make our db accessible to our router
app.use(function(req, res, next) {
req.db = db;
next();
});
app.use('/index3', routes);
app.use('/posts', posts);
app.use('/categories', categories);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Here is the related code from index3.js in the routes folder:
router.get('index3', function(req, res, next) {
var db = req.db;
var posts = db.get('posts');
posts.find({}, {}, function(err, posts) {
res.render('index3', { posts: posts });
});
});
module.exports = router;
Here is the related code from index.js in the routes folder:
router.get('/', function(req, res, next) {
res.render('public/index.html');
});
module.exports = router;
Related
Hi I am trying to send the contents of string stored in mongo db through res.render. However, if I check after sending this string, the tag appears in the form of a string and does not appear in html, so I want to know how to solve it.
router.get("/:id", async function (req, res) {
var article = await Article.findById(req.params.id);
console.log(article);
res.setHeader("Content-type", "text/html");
res.render("articles/article", { article: article });
});
article = "<p>내용입니다.</p>"
here is the working example. You have to install the pug template engine or any other template engine. See the test. pug file and note that if the variable is HTML content then we have to use the syntax "!{para}" or if the variable is a simple string then we can use the syntax "#{para}".
so the folder structure would be like
app.js
views ->test.pug
// app.js file
var express = require('express');
var app = express();
var PORT = 3000;
app.set('view engine', 'pug');
app.use('/', function(req, res, next){
res.render('test', {para : `<p>This is paragraph</p>`});
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
// html file test.pug
<div>!{para}</div>
So, basically I am trying to link two ejs files to express. The first one gets connected and displays result but second one that comes after pressing a button on first one shows error.
The user-list file displays results correctly but the exact same table code shows error in parks
parks.ejs (when I click the link in user-list that redirects here, it says userData not defined)
<div class="table-data">
<h2>Display Data using Node.js & MySQL</h2>
<table>
<tr>
<th>ID</th>
<th>Station N</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<%
if(userData.length!=0){
var i=1;
userData.forEach(function(data){
%>
<tr>
<td><%=i; %></td>
<td><%=data.Station %></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<% i++; }) %>
<% } else{ %>
<tr>
<td colspan="7">No Data Found</td>
</tr>
<% } %>
</table>
</div>
user-list.ejs
hello
++the table code shown above
users.js
var express = require('express');
var router = express.Router();
var db = require('../database');
router.get('/user-list', function(req, res, next) {
db.query("SELECT Station_ID FROM Station WHERE Name = 'A'", function (err, results, fields) {
if (err) throw err;
res.render('user-list', { title: 'User List', userData: results});
});
});
router.get('/parks', function(req, res, next) { //this part not working
db.query("SELECT Station_ID FROM Station WHERE Name = 'A'", function (err, results, fields) {
if (err) throw err;
res.render('parks', { title: 'User Listt', userData: results});
});
});
module.exports = router;
Worth noting is the app.js file because there I had to add app.get("/parks" line to link the two pages otherwise even the link didn't redirect to parks.ejs
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const ejs = require('ejs');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.get("/parks", function(req,res){
res.render("parks");
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
hello
Here, the url is relative to the document root, so this will trigger your app.get("/parks") route handler - which actually doesn't seem to provide a userData variable.
If you want to trigger the router.get('/parks') handler from your user router, you should use a url relative to the current path.
hello
or
hello
I am trying to set up a basic websocket using socket.io on example.com, which runs on a VPS. For the content, I have a index.mjs file and an index.html. I call the html within the mjs:
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
At /var/www/html I can place an html file which will be used when you open example.com.
There is also the root folder, in which I parked the node-modules, index.mjs, package.json and index.html as well.
I had thought I would launch index.mjs from root, which then reads into the index.html at the same file location, but the website remains blank. I am sure that I am missing something here. Any help would be greatly appreciated!
Edit:
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
// can now use `require` in an ESM
const app = require("express")();
const httpServer = require("http").createServer(app);
const options = { /* ... */ };
const io = require("socket.io")(httpServer, {
cors: {
origin: "http://example.com",
methods: ["GET", "POST"],
allowedHeaders: ["my-custom-header"],
credentials: true
}
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on("connection", socket => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});
httpServer.listen(8000);
I have a query inside my controller that it is working but it also work when recibe parameters that doesn't exist
I tried to use HTTP status response code but the result is the same it creates an empty array when you manually type a URL
This is the code inside of Controller
function getPosts(req, res) {
var type = req.params.type;
posts.sequelize.query("SELECT forum.id, forum.forum_type, posts.id,
posts.post_topic_author_id, posts.post_topic_title, posts.forum_type_id
FROM posts, forum WHERE posts.forum_type_id = forum.id AND forum.forum_type = ?", { replacements: [type], type: posts.sequelize.QueryTypes.SELECT }).then(posts => {
res.status(200).send({ posts })
}).catch(err => {
res.status(500).send({ message: 'Ocurrio un error' + err })
});
}
This is the code inside my Routes
const postsController = require('../controllers').posts;
module.exports = (app) => {
app.post('/api/post-create', postsController.create);
app.put('/api/post-update/:id', postsController.update);
app.get('/api/post-get/:type', postsController.getPosts);
}
i need to send the user to something like a 404 page for when he manually tries to enter to a URL that doesn't exist
You can use a middleware to handle error.
for example:
Install hbs
npm install hbs
create a directory views and use this code in app Object:
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
Create a error.hbs file in views directory and add the following code in this file:
Message: {{message}}
Status: {{error.status}}
Stack: {{error.stack}}
catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
I hope it can help you.
am relatively new to expressjs and for the life of me i can not figure out how to navigate between two HTML files in the root folder. Am using bootstrap anjularjs and expressjs for my project.
I have currently used the following code in the routes directory:
var express = require('express');
var router = express.Router();
var app = express();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('profile', { title: 'Express' });
});
router.get('/profile', function(req, res, next){
res.render('profile', {title: ''});
});
module.exports = router;
In addition to this i have also made use of this statement in the app.js file to try and help with navigation:
app.use('/static',express.static(path.join(__dirname, 'views')))
app.use('/html', express.static("html"));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.get('/profile', function (req,res){
res.render('profile', {
title: 'Profile'
});
});
So my problem is this current error, any assistance with this would be appreciated:
Error: Failed to lookup view "error" in views directory "C:\Users\Brian Manda\Documents\fmg_code\views"
at EventEmitter.render (C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\application.js:579:17)
at ServerResponse.render (C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\response.js:960:7)
at C:\Users\Brian Manda\Documents\fmg_code\app.js:52:7
at Layer.handle_error (C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\router\layer.js:71:5)
at trim_prefix (C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\router\index.js:310:13)
at C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\router\index.js:280:7
at Function.process_params (C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\router\index.js:330:12)
at next (C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\router\index.js:271:10)
at C:\Users\Brian Manda\Documents\fmg_code\app.js:41:2
at Layer.handle [as handle_request] (C:\Users\Brian Manda\Documents\fmg_code\node_modules\express\lib\router\layer.js:95:5)
Returns the rendered HTML of a view via the callback function. It accepts an optional parameter that is an object containing local variables for the view. It is like res.render(), except it cannot send the rendered view to the client on its own.
If you dont set the "ejs", automatically the app get the .html file, because res.render is for that.
In the case, my html file have name: index inside public folder.
If your index is .html:
var app = express();
app.get('/', function(req, res){
res.render("../public/index"); //the archive html file
});
If you index is '.ejs':
var app = express();
app.set('view engine', 'ejs'); // set the index.ejs file
app.get('/', function(req, res){
res.render("../public/index.ejs"); // if you want, remove the .ejs, is optional,
});
Reference here.