I have two angular projects and I want to serve them on the same domain like for example if I do mywebsite.com/app1 get the first project and when I do mywebsite.com/app2 get the second project.
If you need them to run on the same node server then just create controller routes for each to separate them. If you mean that you both need them to run on the same physical server then you can look into sub domains and have app1.mywebsite.com point to one running node server and app2.mywebsite.com point to another. This would allow them to be split between 2 node processes.
Simply make 2 folders inside dist for each app and serve the static files using express.static
var express = require('express');
var path = require('path');
var app = express();
app.use('/app1', express.static(path.normalize(__dirname + './../dist/app1')));
app.use('/app2', express.static(path.normalize(__dirname + './../dist/app2')));
create two folder on your node app
app1
app2
put the result of ng build of both project in those folders by editing your angular.json file and specify the outDirand the same for the scond app 'app2' :
"outDir": "/path/to/your/node/app/app2"
"outDir": "/path/to/your/node/app/app1"
then in your node app just tell the app which folder to serve from on the specific route :
app.use('/app1', express.static('app1'));
app.use('/app2', express.static('app2'));
app.use('/', express.static('index.html'));
I have this code now, it is serving the correct app but in Angular it isn't finding the correct js files it's looking in the root directory like localhost:8080/main.js instead it must look at localhost:8080/app1/main.js
const express = require('express');
const app = express();
const path = require('path');
app.use('/app1', express.static(path.normalize(__dirname + '/app/app1')));
app.use('/app2', express.static(path.normalize(__dirname + '/app/app2')));
app.listen(8080, () => {
console.log('Server is litening on port 8080');
});
Related
Background
I am migrating an Angular app in GKE cluster. The base docker image that I must use(company policy) does not have any options to install any new softwares like shell, Angular cli command ng etc. The base docker image has only Node installed.
There is a shared base url, let's say, www.my-company.com, that everyone has to use for app deployment with a path added after the base url like www.my-company.com/my-angular-app/ - all the other Angular apps must be differentiated using the path of the app.
What I did
Since I can't run ng serve command in the base image, I added Express dependency in the package.json in Angular application and created an express server to route the traffic to Angular app.
I was following this youtube video to configure the application - https://www.youtube.com/watch?v=sTbQphoYbK0&t=303s. The problem I am facing is to how I load the the static files in the application.
If I define absolute path inside sendFile method of server.js file, although the application is working, but in future, if I need to add any other files in the application, I have to create another route in server.js file.
I don't know how Express can search a file automatically from the static folder(and sub folders) and return only that file when needed. I defined a static folder too, but seems like it is not working.
Following is my server.js code
==============================
const express = require('express');
const http = require('http');
const path = require('path');
const port = 8080;
const contextPath = '/my-angular-app';
const router = express.Router();
const app = express();
app.use(contextPath, router);
app.listen(port, ()=> {
console.log("Listening on port: ", port);
});
app.use(express.static(__dirname + '/dist/testapp/'));
router.get('/', function(req, res) {
// to get index.html file
res.sendFile(path.resolve(__dirname + '/dist/testapp/index.html'));
});
router.get('/*', function(req, res) {
let path = __dirname +'/dist/testapp/' + req.path
console.log('full path: ', path);
// To return static files based on incoming request, I am facing problem here(I think)
res.sendFile(path);
});
==============================
I want Express will send any files based on file name in the request. It should also take care of nested directories in the /dist/testapp/ directory
/dist/testapp/ -> This is the directory where Angular generates code for my app after I execute ng build command
WEBAPP.get("/admin/script.js", (req, res) => {
console.log(req.path);
if (req.session.username !== "Admin") return res.render("error");
res.sendFile(__dirname + "/admin/admin.js")
});
WEBAPP.get("/admin", (req, res) => {
if (!req.session.loggedin) return res.render("error");
if (req.session.username !== "Admin") return res.render("error",);
res.render("admin", {
csrfToken: req.csrfToken(),
title: "ADMIN PORTAL",
username: req.session.username,
nav_avatar: GetImageURL(req.session.avatar, "small")
});
});
There's no need to publically share /admin/script.js in my case but if a user requests this URL say example.com/admin/script.js a check for username equaling "Admin" if all is okay we sendFile.
I would maybe assume that you're not properly targeting your static files. Perhaps console.log the target.
I am currently working on a nodejs project, and I have a simple question. I want to serve some libraries from my node_modules folder statically to the client (maybe stupid, but not relevant to the question), but I dont want to trash my main server JS file with all these statically served files like this:
const express = require('express');
const app = express();
// Imports here
app.use('/assets/lib/bootstrap', './node_modules/bootstrap/dist');
app.use('/assets/lib/axios', './node_modules/axios/dist');
app.use('/assets/lib/aos', './node_modules/aos/dist');
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
If I have 10+ imports, this would trash up my Server JS file, which I like to keep as clean as possible. I was wondering why this option wouldn't work:
./routes/route1.js :
const express = require('express');
const router = express.Router();
const path = require('path');
// Imports here
router.use('/bootstrap', path.resolve(__dirname, 'node_modules/aos/dist'));
router.use('/axios', path.resolve(__dirname, 'node_modules/aos/dist'));
router.use('/aos', path.resolve(__dirname, 'node_modules/aos/dist'));
// path to node_modules file is not the problem here
module.exports = router
And in my main Server JS file:
const express = require('express');
const app = express();
const route1 = require('./routes/route1');
// Imports here
app.use('/assets/lib', route1);
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
But this gives me an error. The file is not statically served to the client. Is this because an express Router can't serve static files? Maybe this is a rookie mistake, but any help is appreciated. The first code snippet does work, but I'm trying to keep my code organized.
Use the express.static middleware in your route1.js file instead of simply passing the folder path string to the route.
I have an Express app whose server.js file has maybe 30 GET and POST endpoints, like this:
const express = require('express');
const app = express();
const http_port = 8000;
app.listen(http_port,()=>{
console.log(`app listening on port ${http_port}`);
});
app.get('/create_something',function(req,res){
createSomething();
res.send('create');
});
app.post('/update_something',function(req,res){
updateSomething();
res.send('update');
});
//and so on for 30 more endpoints
For ease of maintenance, I want to break this set of endpoints up into different files, e.g. video.js and audio.js.
Thinking this solution might help, I created another file other_route.js:
var express=require('express');
var router=express.Router();
router.get('/other_route_endpoint',function(req,res){
res.send('other_route_endpoint');
});
module.exports.router=router;
and then including this in server.js by changing my initial declarations to:
const express = require('express');
const app = express();
const http_port = 8000;
var router=express.Router();
router.use('/other_route',require('./other_route').router);
But when I visit myserver.com:8000/other_route_endpoint, I get this error:
Cannot GET /other_route_endpoint
How can I add in endpoints from other files into server.js, so I can move some of its many endpoints into these subfiles?
First, your main file should not be using a router. Change the line to app.use('/other_route',require('./other_route').router);.
Second: each path you set with router.use in the routing file will be relative to the path specified in app.use. See https://expressjs.com/en/guide/routing.html#express-router
For example, if you have this in your main file
app.use('/foo', require('./bar.js'));
And this in bar.js
router.get('/bar', /* do something */);
Then the corresponding endpoint would be /foo/bar.
I'm using the cluster module to fork my application in my index.js (which is the main file in my application/root directory of my website). Now my app contains many routes. Should I include the cluster code to wrap all my route files?
For e.g.
Consider my index.js file
var cluster = require('cluster');
if(cluster.isMaster)
{
cluster.fork();
cluster.fork();
cluster.on('disconnect', function(worker)
{
console.error('disconnect!');
cluster.fork();
});
}
else
{
var express = require('express');
var app = express();
app.get('/',function(req,res){
//application logic goes here
});
var route1 = require('./route1.js');
app.route('/route1',route1);
app.listen(80);
}
So ,in my route1.js file, should I wrap it around the cluster-code just as I did around my index.js file or it's not necessary?
Your clusters are the ones who are receiving the http request in the end. They have to know what code, each cluster has to run based on the route. The way you have done it is already correct. If you are taking your project on production you might consider using a process manager like PM2
I am new to NodeJS. What I wanted to know is, can I like call 2 JS files using NodeJS & ExpressJS. Basically I want to have 2 seperate files so I can work on one and my partner can work on another one. So I want Server.js to call one file which contains some part of my REST API and other one contains rest of the function.
|--NodeModules[etc..]
|--Server.js
|--Rest/
| |--RestAPI1.js
| |--RestAPI2.js
It will be really helpful in the development of my project, if this is possible.
You can define routes in different files like this:
Server.js
var express = require('express')
var router1 = require("./routers/router1");
var app = express();
.....
app.use("/user", router1);
Router1.js
var router = require("express").Router();
router.get("/", function(req, res) {
...
});
module.exports = router;