Express Nested Virtual Path Prefix - node.js

I need to run an angularjs application using a virtual prefix on an express server.
index.js
app.use('/foo', express.static('./index.html'))
This works in serving my index.html with the url 'http://localhost:3000/foo', but I need to use 'http://localhost:3000/foo/bar/'
I had thought this line of code would fix that issue, but it just breaks everything.
app.use('/foo', express.static('./index.html'))
Does anyone know how I can do this?
UPDATE
I have managed 'http://localhost:3000/foo/bar' by adding this
const server = express();
const app = express();
server.use('/foo/bar/', app);
But this results in a long list of 404 errors for all my js files. For example:
http://localhost:3000/app/homeCtrl.js

Related

How to manage NodeJs app code to reduce clutter

Hie,
I am developing a Nodejs (Express) web app and pretty much new to this technology. So far I see that there can only be one point of entry mine being my the server.js file. Now it seems all requests and/or processes should be initiated here which is fine for a smaller application, but my site has about 25 page routes already all of who's request should be handle here. I also have a dozen or so Ajax requests are handled here. Now even though I am processing different functions e.g CRUD operations in separate files, I still fear at some point my code will become unreadable as the server.js file get longer
const express = require("express")
const path = require("path")
const exphbs = require("express-handlebars")
let app = express()
app.set("views",path.join(__dirname,'templates'))
app.engine('handlebars',exphbs({defaultLayout:'main'}))
app.set('view engine','handlebars')
app.set('port',(process.env.PORT || 3000));
app.get('/',(req,res)=>{
res.render('home',{'title':'Home'});
});
app.get('/home',(req,res)=>{
res.render('home',{'title':'Home'});
});
app.get('/register',(req,res)=>{
res.render('register',{'title':'Register'});
});
app.use(express.static(path.join(__dirname, '/public')));
app.listen(app.get('port'),()=>{
console.log(`Server started on port : ${app.get('port')}`)
})
So far my server.js is this small, but it just hit me that I have 25 pages and multiple Ajax processes on each.
Yes, you have to structure your routes. For that, you have to look at Express Router. You have to create different route files based on a specific resource.
/routes/homeRoutes.js
const express = require("express");
const router = express.Router();
router.get('/',(req,res)=>{
res.render('home',{'title':'Home'});
});
module.exports = router;
server.js
const homeRoutes = require("./routes/homeRoutes");
app.use("/api/v1/home", homeRoutes);
Also, have a look at the following links for a better understanding of project structure and express router.
https://expressjs.com/en/guide/routing.html
project structure
I think what you are looking for is splitting the code up in local modules. You can place parts of your code in separate files, include module.exports at the end and then require(./filename.js) them in your server.js.
You can see an example here: https://www.tutorialsteacher.com/nodejs/nodejs-local-modules

How to create a node based server to serve REST API and also deploy the application.

I am new to nodeJS server area, need help in understanding how to work with REST API (using express) and deploy the angular application over a singe node server and same ports.
By deploying i want to understand if user hit below url http://localhost:8000/<page_name> then the specified page should open.
And is user hit below url using get or post request
http://localhost:8000/api/<api_name> then a json or a text will be returned.
How to run both the thing over a single node server.
Lets assume, you have all your static files in the /public folder of you app. Generally spoken, if you are using express.static, you should also get your index.html because this is handled by default for each directory.
In your case, as you are using Angular, the routing is handled from the client side (SPA). You should only have one single index.html after building your Angular app. All files from your dist folder should then be placed into your /public folder. Then you need to make sure, that initial file serving provides your index.html like so:
In this example static files are served first, then your API and if nothing is found, you are getting back you index file.
const express = require('express');
const app = express();
// serve static files
app.static(__dirname + '/public'));
// serve your API
app.get('/api/welcome', function (req, res) {
res.send('Welcome');
});
// fallback routing (server side handling)
app.get(/.*/, function (req, res) {
res.sendFile(__dirname + ‘/public/index.html‘
});
app.listen(3000);
Next time please make sure, to give all necessary information in your question ;-)
With the help from Sebastian, so far I can find a solution but its not working when i am hitting URL for different pages.
const express = require('express');
const app = express();
app.use(express.static('public'))
Please provide your suggestions.

Serve both static and apis in express in production

I have deployed a express/vue app to production.
I'm finding a bit difficult to serve both static files and APIs from express.
Inside expressfolder/app.js
const app = express()
const path = require('path')
const serveStatic = require('serve-static')
...
// index.html and static/css, static/js - bundle made with npm run build
const DIR_DIST = path.join(__dirname, '../../path/to/dist')
app.use(serveStatic(DIR_DIST))
...
app.get('/tests', (req, res) => {
res.send({msg: 'Hello there!'})
})
When i go to myapp.com, I see the index.html as desired.
If I type directly in the browser myapp.com/tests I see the raw msg "hello there" from express.
If i call the same route via the link inside index.html, I receive this error in chrome
(failed) net::ERR_CONNECTION_REFUSED
It's working on my local machine, so I'm sure it's some kind of messy config I haven't set properly.
Also, I don't want to be able to access /tests directly: vue-router should override that, but it's a lesser problem.
It's probably been asked before, but it's been a while and I haven't found a solution yet.
Thanks.
The error ERR_CONNECTION_REFUSED is a fundamental networking error that occurs before your server code actually gets to run so that would likely have nothing to do with your specific server code.
It probably happens because you have a bad URL in your web page.

Express router.get fails, yet app.get works

While walking through this tutorial, I came across a problem wherein the router methods would not work. Using npm start and accessing localhost:3000/api/puppies gets a 404 error. However when I changed
var router = express.Router();
router.get('/api/puppies', db.getAllPuppies);
to
var app = express();
app.get('/api/puppies', db.getAllPuppies);
and run with node index.js, the data prints as expected. I've tried also putting at the beginning of my file
app.use(express.static(__dirname + '/api/'));
but no joy. Is this something to do with npm start? At one point I literally copy/pasted the code out of the tutorial and still I get the 404s.
A router has to be connected to your express app in order to be part of your server.
app.use(yourRouter);
Or, more commonly with a path that isolates that router's effect to just URLs that start with a specific path and the router's own URLs are relative to this path:
app.use('/somePath', yourRouter);
Without this, it's just a declared and configured router that isn't attached to any server.
Express documentation examples here.
The tutorial you reference does not appear to show this part of using a router.

NodeJS Express vhosts and updating app.js

I just set up a NodeJS server and wanted to use the vhost function from Express to allow for easy project setup. I want to be able to create a new directory for a new project without going through the hassle of creating new subdomains etc.
Basically, I want to be able to reach project1 at node.domain.com/project1 and project2 at node.domain.com/project2.
I'm now running server.js, which is located in the root (node.domain.com/server.js) and contains:
var express = require('express');
var app = express();
app
.use(express.vhost('node.domain.com', require('./project1/app.js').app))
.use(express.vhost('node.domain.com', require('./project2/app.js').app))
.listen(3000);
It's all working fine, when I go to node.domain.com/project1 I get the results of ./project1/app.js but whenever I change something in any of the app.js files it requires a restart (Ctrl+C followed by node server.js) for it to update the changes.
And the contents of app.js are, for example:
var express = require('express');
var app = exports.app = express();
app.get('/project1', function(req, res){
res.send('Hello World [/project1]');
});
Any idea why this is?
A thing to note is that I also run Apache on the same server, and I'm using this guide to allow both servers to run on port 80 (but accesible via different subdomains).
Oh! I feel dumb now, seems like I need to use something like forever, with its w flag.

Resources