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.
Related
I have the following app with express/socket.io (the app is listening and live without any errors). When I http-request it I get the following error:
GET http://localhost:3030/socket.io/1/?t=1630097351846 404 (Not Found)
And on the socket.io reponse http://localhost:3030/socket.io at I get:
Cannot GET /socket.io
Please help !!
const socket=io.connect('http://localhost:3030/');
//const { Socket } = require("socket.io");
const videoGrid=document.getElementById('video-grid');
const myVideo=document.createElement('video');
myVideo.muted=true;
let myVideoStream
navigator.mediaDevices.getUserMedia({
video:true,
audio:true
}).then(stream=>{
myVideoStream=stream;
addVideoStream(myVideo,stream);
})
// socket.emit('join-room');
const addVideoStream=(video,stream)=>{
video.srcObject=stream;
video.addEventListener('loadedmetadata',()=>{
video.play();
})
videoGrid.append(video);
}
const express=require('express');
const app=express();
const server=require('http').Server(app);
const {v4: uuidv4}= require('uuid');
const io=require('socket.io-client')(server);
//import { io } from "socket.io-client";
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.get('/',(req,res)=>{
res.redirect(`/${uuidv4()}`);
})
app.get('/:room',(req,res)=>{
res.render('room',{roomId :req.params.room});
})
io.on('connection',socket=>{
socket.on('join-room',()=>{
console.log("Room Joined");
})
})
//now need to import socket.io in script.js
// server.listen(app.get('3030'));
app.listen(3030);
<!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>Zoom RJ</title>
<link rel="stylesheet" href="style.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
<!-- <script src="/node_modules/socket.io/client-dist/socket.io.js"></script> -->
</head>
<body>
<div id="video-grid">
</div>
<script src="script.js"></script>
</body>
</html>
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>
Losing my mind here. I feel like I have the paths correct but for some reason my script file isn't loading/working. When I move the code to the app.js it prints out what I want to the console and works just fine but when I have it in the scripts file, it does nothing. I cant seem to find the problem.
app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(express.static(`${__dirname}/public`));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
const rootRoute = require('./routes/index')
app.use('/', rootRoute);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log('server is running')
});
HTML page
<!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">
<title>In Your Words</title>
<link rel="stylesheet" href="/stylesheets/app.css">
</head>
<body>
<script type="text/javascript" src="/scripts/logic.js"></script>
</body>
</html>
script page
const generateInputs = () => {
let randomNumber = Math.floor(Math.random() * 20);
console.log(randomNumber)
}
generateInputs();
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>
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?