res.render not working as expected? doesn't load new pages - javascript

I'm trying to use res.render to load a new page using handlebars, but it doesn't seem to working.
Here are my files:
main.js
var express = require("express");
var exphbs = require('express-handlebars');
var app = express();
app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
app.use('/static', express.static('public'));
var HTTP_PORT = process.env.PORT || 8080;
function onHttpStart() {
console.log("Express http server listening on: " + HTTP_PORT);
}
app.get("/", function (req, res) {
res.render("home")
});
app.get("/roomList", function (req, res) {
res.render('roomList')
});
app.listen(HTTP_PORT, onHttpStart);
Here's the main.handlebars:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/static/css/bootstrap.css" media="screen" charset="utf-8">
<link rel="stylesheet" href="/public/css/custom.css">
<meta charset="utf-8">
<title>Site</title>
</head>
<body>
{{{body}}}
<script src="/static/js/jquery.js" charset="utf-8"></script>
<script src="/static/js/bootstrap.js" charset="utf-8"></script>
<script src="/public/js/custom.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
</script>
</body>
</html>
When attempting to use res.render, nothing happens, despite there being html in home.handlebars and roomList.handlebars
Are there any steps I'm missing?
I have a default navbar in the main file, and it does stay when switching, but nothing new appears.

Related

CSS file is not connecting in an express app

When running my app.js file
const express = require('express');
const path = require('path');
const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Serving on port ${port}`)
})
this is my index.html file is
<!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.0">
<title>Document</title>
<link rel="stylesheet" href="styles.css" type="text/css" />
</head>
<body>
<h1> Testing CSS</h1>
</body>
</html>
then I can not observe the changes of CSS file on the page. But when I open the HTML file with live serever I can see the CSS changes why is this happening.
When I am running my app.js file css is not connecting. But when I open the HTML file with live server CSS file is connecting. What is the reason behind this ??
app.use(express.static(path.join(__dirname, 'public')));
include this in your app.js create a folder called public and put the style.css in your public directory.
your code would be
const express = require('express');
const path = require('path');
const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.use(express.static(path.join(__dirname, 'public'))); //<-here
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Serving on port ${port}`)
})

Error: GET js file net::ERR_ABORTED 404 (Not Found) node.js

I know that this question is not first but I don't know where to look for solution.
I have an express backend server. It has to render HTML page with main.js in it when it launches.
app.js code:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
// <...>
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.set('views', path.resolve(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.resolve(__dirname, 'public')));
var listener = app.listen(5000, function(){
console.log('Listening on port ' + listener.address().port);
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
// 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;
public/index.html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"
type="text/css">
<link rel="shortcut icon" href="./favicon.ico" type="image/x-icon">
<title>Fetch Travels</title>
<style>
#play {
display: none;
}
</style>
</head>
<body>
<button type="button" class="btn btn-primary" id="play">search</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="main.js" type="module"></script>
</body>
</html>
public/main.js obviosly is a client script that is not found on a server but found in localhost.
change it to something like this
<script src="/main.js" type="module"></script>

"Error: No default engine was specified and no extension was provided" When trying to do Server Side Rendering in React

Hi I'm trying to do server-side rendering in my react app but I get the error
Error: No default engine was specified and no extension was provided.
I've got an ejs template index.ejs:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello Redux</title>
<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/cyborg/bootstrap.min.css" rel="stylesheet" integrity="sha384-D9XILkoivXN+bcvB2kSOowkIvIcBbNdoDQvfBNsxYAIieZbx8/SI4NeUvrRGCpDi" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app"><%- myHtml -%></div>
<script src="bundle.js"></script>
</body>
</html>
A request handler function:
'use strict'
import axios from 'axios'
function handleRender(req, res){
axios.get('http://localhost:3001/books')
.then(function(response){
var myHtml = JSON.stringify(response.data);
res.render('index', { myHtml })
})
.catch(function(err){
console.log('#Initial Server-side rendering error', err);
})
}
module.exports = handleRender;
And in app.js I require the request handler function and set it:
app.set('view engine', 'ejs');
app.use(requestHandler);
Can anyone help me with this issue? The link to my github repo with all the code is at https://github.com/edward-hong/book-shop
in app.js
var app = express();
app.use(logger('dev'));
var apiProxy = httpProxy.createProxyServer({
target: 'http://localhost:3001'
});
app.use('/api', function(req, res){
apiProxy.web(req,res)
})
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
just move app.set('view engine', 'ejs') and put it right after var app = express()
apiServer.js is your entry, so you need to explicitly app.set('view engine', 'ejs') there

How to link an existing Angular 2 app to Nodejs Server?

I have an Angular 2 app with this structure :
Structure of my Angular app
Then in server side :
Structure of server app
I see that there is 2 module dependencies folders, but I don't know which one I sould keep.
Here is my index.js file :
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
// Get our API routes
//const api = require('./server/routes/api');
const app = express();
// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'client/portfolio')));
// Set our api routes
//app.use('/api', api);
// Catch all other routes and return the index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client/portfolio/src/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3001';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`API running on localhost:${port}`));
When I start server I get this message :
Loading AppComponent content here ...
But it stops here and doesn't render the Angular application.
index.html file :
<!DOCTYPE html>
<html>
<head>
<title>Angular QuickStart</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<link href="node_modules/#angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/hammerjs/hammer.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('main.js').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading AppComponent content here ...</my-app>
</body>
</html>
Here's a good example of integrating AngularJS with NodeJS [open tutorial]
The trick is in this block
/* GET home page. */
router.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});

Angular : Uncaught ReferenceError: app is not defined

I am trying to create this very simple meanstack app and its almost running but with an uncaught reference error when it is redirecting to index page. Server is running ok. Browser is showing the text (Loading..) as in the index page. But as the custom tag should have gone along with the selector to app.component.ts and printed "My First Angular App", it doesn't. Instead it is saying in console that "app is not defined".
Can anyone help? I am new to MEAN & Angular, so kindly elaborate. And please excuse my silly mistakes if there are any (or many).
This is my index.html
<html>
<head>
<title>MyTaskList</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>System.import(app).catch(function(err){ console.error(err);});</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
this is my app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: 'My First Angular App'
})
export class AppComponent { }
my index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next){
res.render('index.html');
});
module.exports = router;
and finally my server.js (starting point)
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var tasks = require('./routes/tasks');
var port = 3000;
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'client')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('/api', tasks);
app.listen(port, function(){
console.log('Server started on port '+port);
});
Put app in quotes because Javascript thinks app is a variable but it should actually be a string.

Categories