node js res.render does not work, but res.send does - javascript

I am setting up the environment for a node js app. But the views/ejs files are not being rendered.
If i do:
app.get("/", function(req, res){
res.send('Hello');
});
it works.
But if i do:
app.get("/", function(req, res){
res.render("welcome");
});
it doesn't.
my app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const indexRoutes = require("./routes/index");
const userRoutes = require("./routes/user");
const ejsLayouts = require("express-ejs-layouts");
const path = require("path");
mongoose.connect("mongodb://localhost/userAuth", function(err, res) {
if (err) throw err;
console.log("Connected to database");
});
//EJS
app.set('view engine','ejs');
app.use(ejsLayouts);
app.use(express.static(__dirname + '/public'));
app.set('views',path.join(__dirname+'/views'))
//ROUTES
app.use("/", indexRoutes);
app.use("/user", userRoutes);
app.listen(3000, function() {
console.log("server started");
});
my index.js file (userLogin/routes/index.js)
const express=require("express");
path = require('path');
router= express.Router();
router.get("/",function(req,res){
res.render("welcome");
});
module.exports = router;
my folder structure
userLogin
/..
/routes
/index.js
/views
/welcome.ejs
I have an h1 element olny in welcome.ejs file.

Looking at the code you provided, in index.js you are trying to render a view called check, when the only view you have is called welcome. Your paths and routes look to be correct, rendering the correct view should work.

app.engine('html', require('ejs').renderFile);
if u woudlike to render .html files
then
fs.readFile(path.resolve(__dirname + '/../public/views/logs.html'), 'utf-8', (err, content) => {
let renderedHtml = ejs.render(content, {'user': req.session.db}); //get redered HTML code
res.end(renderedHtml);
})

you should have views/layouts/layout.ejs file if you are using express-ejs-layouts npm
inside app.js :
const ejs =require('ejs');
const ejsLayouts = require("express-ejs-layouts");
app.set('view engine','ejs');
app.use(ejsLayouts);
app.set('layout', 'layouts/layout');
layout.ejs file has common layout that follow all files
if you are using bootstrap then your layout.ejs file would be like :
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<title></title>
</head>
<body>
<?- body ?>
</body>
</html>
so now other ejs pages will only have content to display
like welcome.ejs file is
<h1>Welcome Page</h1>

Related

Can't load/find files on server with node.js, 404 error (not found)

I'm trying to load a script.js and a style.css file on the server. The index.html and index.js work fine, however, there seems to be an error when I try to load the style.css file and script.js file, which I use for backend.
GET http://localhost:4000/script.js net::ERR_ABORTED 404 (Not Found)
All my files are in the same directory, /public.
I already checked the CSS file, and it loads when I display the HTML file when it's not on the server.
This my index.js file:
const express = require('express');
const cors = require('cors');
const fs = require('fs')
const ytdl = require('ytdl-core');
const app = express();
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))
app.use(cors());
app.listen(4000, () => {
console.log('Server works at port 4000');
});
app.get('/', function(req,res){
res.sendFile(__dirname + '/index.html');
});
app.get('/download', (req,res) => {
var URL = req.query.URL;
res.json({url:URL});
})
The HTML file:
<!DOCTYPE HTML>
<html lang="en">
<head>
<link href="/style.css" rel="stylesheet" type="text/css"/>
<meta charset="UTF-8">
<title>PyTube</title>
</head>
<body>
<h1>PyTube</h1>
<input type="url" name="yturl" class="URL-input" id="yturl" placeholder="https://www.youtube.com/watch?v=" required>
<button class="convert-button">Convert</button>
</body>
</html>
<script src="script.js"></script>
I've tried a bunch of things and trying things with __dirname and paths, but I can't find the issue or fix it.

Not reading the CSS - Express ejs layouts

I am using the express ejs layouts but only the mainPage can read the css the other pages don't read it (the css, the html read it).
Another question, if I wanted to use another layout (ex: layout2.ejs) what would i do to act on a specific page.
Tree:
Project
- public
- js
- css
- style.css
- routes
- index.js
- users.js
- views
- layout.ejs
- mainPage.ejs
- login.ejs
...
- app.js
I am using particles.js if you need to know.
app.js
const express = require('express');
const expL = require('express-ejs-layouts');
const app = express(); //Create a Web Application
//EJS
app.use(expL);
app.set('view engine', 'ejs')
//Routes
app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));
app.listen(3000, ()=> console.log('Listening at 3000'));
app.use(express.static('public'))
index.js
const express = require('express');
const router = express.Router();
router.get('/',(req, res) => {
res.render('mainPage',{title: 'Groupy'}); (THIS ONE WORK AND READ THE CSS)
});
module.exports = router;
users.js
const express = require('express');
const router = express.Router();
//Login Page
router.get('/login',function(req, res) {
res.render('login',{title: 'Groupy Login'}); (DON'T READ CSS)
});
//Register Page
router.get('/register',function(req, res) {
res.render('register',{title: 'Groupy Register'}); (DON'T READ CSS)
});
module.exports = router;
layout.ejs
<html>
<head>
<script type="text/javascript" src="code.js"></script>
<link rel="stylesheet" type="text/css" href="./css/style.css">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
</script>
<title><%= title %></title>
</head>
<body>
<div id="particles-js"> </div>
<script src="js/particles.min.js"></script>
<script src="js/app.js"></script>
<h2>teste</h2>
<%- body %>
</body>
mainPage.ejs
<h1 id="title">Groupy</h1>
<div id="firstBox">
<div id="SignIn">Register <div id="login">Login</div>
</div>
</div>
<br>
<div id="mainBox"></div>
login.ejs
<h1 id="title">Groupy Login</h1>
Reseult of login (without CSS):
teste
Groupy Login
Can you try the following app.use instead of app.use(express.static('public'))
app.use('/public', express.static(path.join(__dirname, 'public')));
Also you should import path module
const path = require('path');
The error was the path of css and javascript (particles.js)
<link rel="stylesheet" type="text/css" href="/css/style.css">
<script src="/js/particles.min.js"></script>
<script src="/js/app.js"></script>

Not getting the external js/css files using Angularjs and Node.js

I could not find the external js/css files using Angular.js and Node.js. I am explaining my code below.
Node/app.js:
require('./config/config');
require('./models/db');
require('./config/passportConfig');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const rtsIndex = require('./routes/index.router');
var app = express();
var morgan = require('morgan');
var methodOverride = require('method-override');
var appRoot = require('app-root-path');
var path=require('path');
var reqPath = path.join(__dirname, '../');
console.log('app',reqPath + 'angularjs/dist');
//var corsOptions = {"origin": "http://localhost:4202", "methods": "GET,PUT,DELETE,POST", "preflightContinue": false, "optionsSuccessStatus": "204"};
//app.use(cors(corsOptions));
// middleware app.use( bodyParser.urlencoded({ extended: true }) );
app.use(bodyParser.json());
app.use(cors());
app.use(passport.initialize());
app.use('/api', rtsIndex);
app.use(express.static(reqPath + 'angularjs/dist/')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ extended: false,limit: '5mb' })) // parse application/x-www-form-urlencoded
app.use(methodOverride()); // simulate DELETE and PUT
app.get('/',function(req,res){
res.sendFile(reqPath+'angularjs/index.html');
});
// error handler
app.use((err, req, res, next) => {
if (err.name === 'ValidationError') {
var valErrors = [];
Object.keys(err.errors).forEach(key => valErrors.push(err.errors[key].message));
res.status(422).send(valErrors)
}
else{
console.log(err);
}
});
// start server
app.listen(process.env.PORT, () => console.log(`Server started at port : ${process.env.PORT}`));
The above is my server side code and my client side code is given below.
angularjs/index.html:
<!DOCTYPE html>
<html lang="en" ng-app="lendingkart">
<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>Welcome to Lendingkart</title>
<link rel="icon" href="dist/images/favicon.png" />
<!--Plugin CSS-->
<link href="dist/css/plugins.min.css" rel="stylesheet">
<!--main Css-->
<link href="dist/css/main.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js"></script>
<script src="dist/js/angularjslatest.js" type="text/javascript"></script>
<script src="dist/js/angularuirouterlatest.js" type="text/javascript"></script>
<script src="dist/js/route.js" type="text/javascript"></script>
<script src="dist/js/angularcaps.js" type="text/javascript"></script>
<script src="dist/js/angular-messages.js" type="text/javascript"></script>
<script src="dist/js/angularuibootstrap.js" type="text/javascript"></script>
<script src="dist/js/ng-file-upload-shim.min.js"></script>
<script src="dist/js/ng-file-upload.min.js"></script>
<script src="dist/js/dirPagination.js"></script>
<script src="dist/js/angular-chosen.min.js"></script>
</head>
<body>
<div ui-view>
</div>
<!-- jQuery -->
<script src="dist/js/plugins.min.js"></script>
<script src="dist/js/common.js"></script>
<script src="dist/js/jquery.mousewheel.min.js" charset="utf-8"></script>
<script src="dist/js/raphael.min.js" charset="utf-8"></script>
<script src="dist/js/jquery.mapael.js" charset="utf-8"></script>
<script src="dist/js/india.js" charset="utf-8"></script>
</body>
</html>
Here I am using the UI-ROUTER for get the pages.
angularjs/dist/route.js:
var Admin=angular.module('lendingkart',['ui.router', '720kb.datepicker','ngMessages','ngCapsLock','ui.bootstrap','ngFileUpload','angularUtils.directives.dirPagination','angular.chosen']);
Admin.run(function($rootScope, $state) {
$rootScope.$state = $state;
});
Admin.config(function($stateProvider, $urlRouterProvider,$locationProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/',{
url: '/',
templateUrl: 'views/login.html',
controller: 'loginController'
})
})
Here my issue is when index page is loading it could not get the external files and getting this GET http://localhost:3003/dist/css/plugins.min.css net::ERR_ABORTED error. As i am using two diferent folder for node.js and angular.js then I am getting these issues. I need to resolve those issues and access the required pages.

Angular 2 Syntax Error Uncaught token during refreshing page with inner directory on URL - Nodejs Express

I am trying to open a page with inner directory such as localhost:1000/register/100 using Angular 2. On button click to navigate to that URL works perfectly but going to that page manually by typing on the URL or refreshing that page will give syntax error uncaught token
The URL of the files on that error are stated
localhost:1000/register/node_modules/....
localhost:1000/register/systemjs.config,js/....
it seems that it is not getting node_modules and systemjs path correctly.
From my research, there are many who are encountering the same problem but without a solution. Is there a way to go around this?
server.js
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
path = require('path'),
passport = require('passport'),
session = require('express-session'),
port = process.env.PORT || 1000;
db = require('./config/db');
mongoose.Promise = global.Promise;
mongoose.connect(db.url);
app.use(session({
secret: 'test',
saveUninitialized: true,
resave: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
require('./config/passport')(passport);
require('./routes/main')(app, passport);
app.use(express.static(path.join(__dirname)));
app.use('/node_modules', express.static(__dirname + '/node_modules'));
app.all('/*', function (req, res, next) {
res.sendFile('/view/index.html', { root: __dirname });
});
app.listen(port);
console.log('Magic happens on port ' + port);
I've also added
app.use('/node_modules', express.static(__dirname + '/node_modules'));
index.html
<head>
<title>MET2U</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
<!-- 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>
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function (err) { console.error(err); });
</script>
</head>
<body>
<base href="/">
<my-app>Loading AppComponent content here ...</my-app>
</body>
</html>
but nothing seems to be working.
Am I missing something?

Vue-resource can't load express static file

So, I have a bit of a problem. Here's my server.js
require('dotenv').load();
const http = require('http');
const path = require('path');
const express = require('express');
const app = express();
const server = http.createServer(app).listen(8080, () => {
console.log('Foliage started on port 8080');
});
app.use(express.static(path.join(__dirname, '/public')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
What this does, is that for every /whatever it gives the index.html file. Alongside that, it serves static files from /public Now, my index.html looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Foliage</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/foliage.css" media="screen" title="no title">
<script src="https://use.fontawesome.com/763cbc8ede.js"></script>
</head>
<body>
<div id="app">
<router-view :key="$router.currentRoute.path"></router-view>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script src="js/md5.js"></script>
<script src="js/cookies.js"></script>
<script src="js/dragula.js"></script>
<script src="js/build.js"></script>
</body>
</html>
All of the JS files and the style files are loaded appropriately from public/jsand public/css for this. However, in build.js, which is a webpack-ed vuejs app, I use vue-resource, to load in another file from public/themes/Bareren/templates. That looks like this
page = {};
page.Template = "Index";
this.$http.get('themes/Barren/templates/'+page.Template+'.html').then((response) => {
console.log(response.body);
});
However, this request does not give me the file in public/themes/Barren/templates. It instead gives back the site's own index.html file. How could i fix this?
app.use(express.static(path.join(__dirname, '/public')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html')); });
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html')); });
Try to console.log(path.join(__dirname, '/public')) and console.log(path.join(__dirname, 'index.html') to see if the path matches what you are expecting.
this.$http.get('themes/Barren/templates/'+page.Template+'.html').then((response)
=> {
console.log(response.body); });
You can also try console logging your get request. Usually I need to play with the pathing to making sure I'm serving the correct files.
One thing you can try is to define a GET route which responds with your template before the wildcard at the bottom.
app.get('/themes', (req, res) => {
// get the theme name
res.sendFile(path.join(__dirname, ... ));
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});

Categories

Resources