How to add Express route endpoints from another .js file? - javascript

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.

Related

Accessing local json files from the browser using NodeJs backend

I am working on a react application that takes the json file path as a parameter to render the json data in my ui. Accessing local files from the browser is restricted, so how can I create a backend server to retrieve my local json files and serve them to the browser?
you can boot up a local server using express, and use the fs module to access file content
const fs = require('fs');
const file_content = fs.readFileSync('./{file_name}',
'{content_formate}').toString();
// For show the data on console
console.log(file_content);
To create a server that is listening on port 3000, use
const express = require('express')
const fs = require('fs');
const app = express()
const port = 3000
app.get('/', (req, res) => {
const file_content = fs.readFileSync('./{file_name}',
'{content_formate}').toString();
res.send(file_content)
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
something like this
To access local json files in your swagger application, you need to use express - as the browser cannot access your local file system. You can create an endpoint, i.e. '/swagger', that will allow you to serve the files from the directory provided. In the urls parameter, you will use '/swagger/name.json', rather than the local path. Create a driver.js file with the following content:
var express = require('express');
var app = express();
app.use('/swagger', express.static('/path/to/local/files'));
app.listen(3000);

Express serve static files inside Router

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.

How to serve static files in ExpressJS on some paths and not others

How can I serve static files with ExpressJS only from some of paths, while not for others?
To be more specific, I want to serve static files from all paths except /files (in case of request to this path, I want only to edit some file on the server).
I have this piece of code:
var express = require('express');
var app = express();
express.static(__dirname);
app.use(redirectUnmatched);
function redirectUnmatched(req, res) {
//Do something on server
console.log("req.url:"+req.url+"<br>"+__dirname);
}
let port = 80;
var server = app.listen(port);
But I really don't know, how to edit my code to do that...
Can anyone help me?
Thanks!
Just defining the /files route before serving the static files might work:
// Define `/files` route first
app.use("/files", function (req, res) {
return res.send("I will be served instead of a files directory");
});
// Static
app.use("/", express.static(__dirname));
const express = require('express');
const path = require('path');
const app = express();
app.use('/public',express.static(path.join(__dirname,'static')));
app.get('/',(req,res)=> {
res.sendFile(path.join(__dirname,'static','index.html');
});
app.listen(3000);

How to properly access the app variable set by express in a node.js app?

I'm building a node.js server and my folder structure looks like this:
server.js
app/routes.js
app/routes/users.js
My problem is that i'm not sure how can i use the app variable inside the users.js file. Do i have to require and setup express again in this file or is there a better/easier way to do it? Here is my sample code(just the bare minimum to understand my problem):
server.js
// Include our packages in our main server file
var express = require('express');
var stormpath = require('express-stormpath');
var app = express();
// Init Stormpath for user management and authentication
app.use(stormpath.init(app));
// Load routes
require('./app/routes')(app);
// Start the server
app.listen(process.env.PORT);
// Stormpath will let you know when it's ready to start authenticating users.
app.on('stormpath.ready', function () {
console.log('Your server is running on port ' + port + '.');
});
app/routes.js
// Import dependencies
const express = require('express');
const stormpath = require('express-stormpath');
// Export the routes for our app to use
module.exports = function(app) {
// Create API group routes
const apiRoutes = express.Router();
// User management: get users, invite users, view user profile
var UsersRoute = require('./routes/users');
apiRoutes.get('/memberinfo', stormpath.loginRequired, UsersRoute.memberInfo);
// Set url for API group routes
app.use('/', apiRoutes);
};
app/routes/users.js
// Protected route test
module.exports.memberInfo = function(req, res){
//how do i access the "app" here?
res.status(200).send({ user: req.user });
}
In your .memberInfo method, you can use req.app to access the app object that is associated with that request.
In cases where you aren't passed a req object that you can use in this way, then you need to initialize the module by calling a method on it and passing it the app object and the module can then store the app object locally so it can use it when desired.

node how can My app find index.js

Folder structure
bin - www.js
lib - jsFiles...
models - jsFiles...
node_modules -Folders and Files
public - index.html
route - jsFiles...
index.js
package.json
I use Express, angular.js. Server starts at www.js and It calls
index.js. After that, When I type merely "localhost:3000" It shows me
public/index.html. I don't have route for '/' but It shows me
'public/index.html'. I can not understand this. Please let me know
about the process.
www.js
var debug = require('debug')('example-server');
var app = require(process.cwd()+'/index');
//listen at 3000 port
app.set('port',process.env.PORT || 3000);
var server = app.listen(app.get('port'),function()
{
debug('Express server listening on port ' + server.address().port);
});
index.js
var favicon = require('serve-favicon');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//Connection for DB
require('./lib/connection');
var employees = require('./routes/employees');
var teams = require('./routes/teams');
var app = express();
// Writing at routing table
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname,'public')));
app.use(employees);
app.use(teams);
// send 404 to errorhandler
app.use(function(err,req,res,next)
{
var err = new Error('Not Found');
err.status = 404;
console.log(error);
next(error);
});
...
...
module.exports = app;
In express.js the sequence in which you register your middleware makes a huge difference.
When express.js receives a request, it starts from top and executes registered middleware.
Middlewares are registered in express app using app.use(middleware_goes_here) this type of middleware gets executed no matter what the request url is on the other hand you can also register a middleware like app.use('/url/path',middleware_goes_here) in this case we are registering this middleware to '/url/path' so this middleware will only get executed when you visit '/url/path' (and non of the previous matching middleware serves the request without calling next() )
This app.use(express.static(path.join(__dirname,'public'))); line of code does the magic.
You can go here (express.static ref) to know more about static content serving and routing.
Basically what happens is, we are configuring express.static middleware to serve static content "as is" from "public" folder. So when you make any request and it matches a static content in public folder, then it will serve it otherwise express.static will call next middleware in sequence.
So in your case, the first middleware that actually server input request is express.static without any route filters, so it servers index.html even without a specifically defined route. If your public folder had file at public/javascript/jquery.js then following url will map to it http://localhost:3000/javascript/jquery.js
NOTE: You do not have to specify "public" in the url, the way in which express.static is registered, it will server contents FROM "public" folder.
................
UPDATE: How does default work in express.static?
By default, app.use(express.static(path.join(__dirname,'public'))); this will take index.html as default document. If you want to set index2.html as your default document, you can do that by doing something like this app.use(express.static(path.join(__dirname,'public'),{index: 'index2.html'}));
Hope it helps.
Put a relative path to folder(one up in hierarchy).
var app = require('../index');

Categories

Resources