how to render html page in loopback - node.js

hello guys i m new to loopback, can anyone help me with this following things
when we install loopback by default we have client folder when we can place all our front end file now place all html file there and render these html file from router for eg ;-
var router = server.loopback.Router();
router.get('/', function(req, res) {
res.render('index');
});
router.get('/login', function(req, res) {
res.render('login');
});
i want something like this i have index,login html file in client folder so how i can do that i does lots of google but haven't find any soultion like this

Assuming you created your project via loopback's CLI, you should have a server/boot/root.js file.
'use strict';
module.exports = function(server) {
// Install a `/` route that returns server status
var router = server.loopback.Router();
router.get('/', server.loopback.status());
server.use(router);
};
Either remove or change the route to server.loopback.status() (e.g. router.get('/status', server.loopback.status()).
In server/middleware.json, you should see a line near the bottom with "files": {},.
Modify it to the following:
"files": {
"loopback#static": {
"params": "$!../client"
}
},
Place all your static files into the client directory.
This is from loopback's documentation: Add a static web page. I'd recommend going through all the Getting started with LoopBack documentation if you are new.

Just posting the answer so that it may work for the people for whom the Previous answer din work, I would like to suggest some other approach that worked for me.
inside server/boot/root.js file add the below code:
'use strict';
const path = require('path');
module.exports = function(server) {
// Install a `/` route that returns server status
const router = server.loopback.Router();
router.get('/', (req, res, next) => {
res.sendFile(path.join(__dirname,'./../../client','index.html'));
});
server.use(router);
};

Related

How to split a routes.js that grows too large to be easily maintained?

I'm using node and express to create a rest api. I followed a tutorial where all the routes and its logic are saved in a routes.js file like this:
SERVER JS:
var express = require('express');
var app = express();
(...)
require('./app/routes.js')(app, port, express);
ROUTES.JS
module.exports = function(app, port, express) {
var apiRoutes = express.Router();
(...)
//Sample route
apiRoutes.get('/userfiles', function(req, res) {
UserFile.find({ owner: req.decoded.user.email }, function(err, filesList) {
if (err)
return done(err);
res.json({ success: true, files: filesList });
});
});
My problem is twofold:
1 - Routes can easily contain code thats 150 lines long, some of them far longer. It doesn't feel clean to have route declarations and the logic grouped together. Is it a good practice to do something like this instead?
apiRoutes.post('/randomRoute', function(req, res) {
return res.json(functionThatContainsTheActualCode(req));
});
(and then have an functionThatContainsTheActualCode function with all the logic in a different file).
2 - I have middleware that applies to some functions (for example, some routes are only accessible for logged in users and those routes go through an authentication middleware). Currently way I do it is declaring public routes before the middleware declaration and private routes after, which feels incredibly hacky. How can I separate public and private routes (and the middleware itself) in different files?
Problem 1:
We need to go deeper.
Change the route file to just require the actual router logic.
routes.js
// where app = express();
module.exports = (app) => {
// index.js happens to be a file exporting the router.
app.use('/', require('./index'));
// this is basically the idea. Create a separate file for the actual logic.
app.use('/route', require('.path/to/file'));
};
and in file.js
const express = require('express'),
router = express.Router();
router.verb('/path/', (req, res, next) => {
// do whatever
});
// this is required
module.exports = router;
Problem 2:
Middleware is basically a function taking in request, response, next as 3 params, doing something with the request and either sending out a response or moving on to the next middleware. That's why you need to call next if you want to move to next middleware in the chain.
Now all you need is a file that exports a function which takes request, response, next as params.
// lets call this auth.js
module.exports = function(req, res, next) {
// do logic
if () {
return res.send(); // or res.somethingThatSendsOutAHttpResponse()
}
// next middelware
next();
};
Since express routes are also middlewares, (mind blown), you can mount them top down.
To authenticate a route, just put the auth.js middleware on top of that route.
router.get('/', require('./auth'));
router.get('/', require('./log'));
router.get('/', (req, res, next) => {
// yolo
});
Now since this is web dev, you still got problems.
Now all your boring database queries are scattered everywhere.
Fear not, you can solve it, by, guess, creating another file.
apiRoutes.get('/userfiles', function(req, res) {
const userFile = require('/path/to/model/with/userfile/methods/exported/out');
// do something with userFile's methods
});

Node / Express - Is there a way to access static files from a controller method?

Inside the controller method, is there a way to access static files? I am using mailgun to send emails and need to send an html file in my request that is located in /public.
app.post('/', function(req, res) {
var html = getHtml(); // Need to get the html here to pass to mailgun
}
Is there a way to access the static file dir using some handy device provided by Express? No, not that I'm aware of.
Is there a way to get what you're trying to do done? Sure. Read it with the fs module. I like to use the path module, too, to generate my path to the file.
const path = require("path");
const fs = require("fs");
// Do however you like to build paths.
// I like to use resolve so I always get an absolute path.
const publicPath = path.resolve(__dirname, "public");
const htmlPath = path.join(publicPath, "thefile.html");
app.post('/', function (req, res, next) {
fs.readFile(htmlPath, "utf8", onFile);
function onFile (err, html) {
if (err) return next(err); // assuming you're using an error handler, like you probably should be
mailgunThatStuff(html, mgDone);
}
function mgDone (err) {
if (err) return next(err);
res.end("OK mailgun'd that thing");
}
}
That's a little wordy, maybe. Make sense?
you can try this
(app.js) you just mention static folder in app.js
var express = require('express');
var app = express();
app.use(express.static('public'));
index.html page in local flower in ./public/pages/
app.all('/', function (req, res) {
res.sendFile('index.html', {root: './public/pages/'});
});
try this its working fine

Move routes into files in Express.js

Say I have some routes (I have a lot more, but this should explain):
router.post('/post');
router.get('/post/:id');
router.get('/posts/:page?');
router.get('/search');
For the /post ones I know I could do something like
app.use('/post', postRoutes)
Where postRoutes is the actual post routes in another file. However, I'd like to group all post related routes into a postRoutes component (so /post and /posts), search into a search component and so on. Is there a way to do something like
router.use(postRoutes); // includes routes 1-3 above
router.use(searchRoutes); // only the 4th route above
And so on? That would let me keep the top level file much cleaner.
Yes it is simple. You can even make more nesting levels. I think it is good to separate routes, especially when you have dozens of routes.
in your first file (server.js)
app.use(require("./allpost"));
app.use(require("./allqueries"));
in allpost.js
var express = require('express');
var router = new express.Router();
router.post('/post', function (req, res) {
//your code
});
router.get('/post/:id', function (req, res) {
//your code
});
router.get('/posts/:page?', function (req, res) {
//your code
});
when you want more nesting
router.use(require("./deeper"));
or when you want use path part
router.use("/post2/", require("./messages/private"));
module.exports = router;
You could do that by creating a special route file. Here's an example of such file
module.exports = (function() {
var express = require('express');
var router = express.Router();
router.get("/:id", function (request, response, next) {
request.body.id = request.params["id"];
// Do something ...
});
router.post("/someRoute", function (request, response, next) {
// Do something ...
});
// And so on ...
return router;
})();
Next, in you server.js file, include it like this
app.use('/post', require('./routes/postRoutes'));
The problem was I was thinking about this wrong. First off, don't use singular and plural. It makes it a headache and also makes it hard for people to remember the API.
Once I used all plural I had a setup like this in my index.js file:
// The API routes all start with /api and we pass app here so we can have some
// sub routes inside of api
app.use('/api', require('./app/api')(app));
And then in my api/index.js
var express = require('express');
var router = express.Router({ mergeParams: true });
var routeInit = function (app) {
app.use('sessions', require('./sessions')(router));
app.use('users', require('./users')(router));
return router;
};
module.exports = routeInit;
You can see that I'm passing the router manually each time. Then finally:
var routeInit = function (router) {
router.post('/blah', function (req, res, next) {
// Do stuff
});
return router;
};
module.exports = routeInit;
This allowed me to nest routes infinitely deep.

Express 4 Route Issues

Just learning nodejs, express, jade. While making progress, I am having trouble understanding how the routes work. I have the routes in a routes folder and the views (Jade files) in a views folder. And that works, but I don't see how.
Let's say I have a page foo. In routes, I have foo.js:
var express = require('express');
var router = express.Router();
/* GET foo page*/
router.get('/', function(req, res) {
res.render('foo', {title: 'Foo' });
});
module.exports = router;
The menu link in the Jade file that calls Foo has an href="/foo" attribute. How come router.get('/', ... ) works? Shouldn't it have to be
router.get('/foo', function(req, res) {
res.render('foo', {title: 'Foo' });
});
When I try to do that, however, it can't find the route and I get a 404, which seems counter to the router docs. I could just go with it and have all the routes get('/', ...) or post('/', ...), which does work, but it just seems wrong.
What am I missing?
Thanks for your insight.
Your app.js file probably contains a line that looks like the following:
app.use('/foo', require('./routes/foo'));
This means that any route defined in ./routes/foo will be relative to /foo. Therefore, your / route is accessed via /foo/.

Express Routes in Parse Cloud Code Module

I am using parse.com cloud code with express to setup my routes. I have done this in the past with node, and I have my routes in separate files. So, in node I do
app.js
express = require("express");
app = exports.app = express();
require("./routes/js/account");
account.js
app = module.parent.exports.app;
app.get("/api/account/twitter", passport.authenticate("twitter"));
All the examples on parses site https://parse.com/docs/cloud_code_guide#webapp show this being done as follows.
app.js
var express = require('express');
var app = express();
app.get('/hello', function(req, res) {
res.render('hello', { message: 'Congrats, you just set up your app!' });
});
So, I would like to change the bottom to include a routes folder with separate routes files, but am not sure how to do this in parse.
I know this post is a little old, but I just wanted to post a solution for anyone still looking to get this to work.
What you need to do, is create your route file, I keep them in 'routes' forlder, for example <my_app_dir>/cloud/routes/user.js
Inside user.js you will have something that looks like this:
module.exports = function(app) {
app.get("/users/login", function(req, res) {
.. do your custom logic here ..
});
app.get("/users/logout", function(req, res) {
.. do your custom logic here ..
});
}
Then, in app.js you just include your file, but remember that you need to append cloud to the path, and pass the reference to your app instance:
require('cloud/routes/user')(app);
Also, remember that express evaluates routes in order, so you should take that into consideration when importing several route files.
I'm using a different method, have the routes in app.js, but you can probably include them in file if you prefer. Take a look at the example app,
anyblog on github
The way it works:
Set up a controller:
// Controller code in separate files.
var postsController = require('cloud/controllers/posts.js');
Add the controller route
// Show all posts on homepage
app.get('/', postsController.index);
// RESTful routes for the blog post object.
app.get('/posts', postsController.index);
app.get('/posts/new', postsController.new);
And then in posts.js, you can use exports, ex.
var Post = Parse.Object.extend('Post');
// Display all posts.
exports.index = function(req, res) {
var query = new Parse.Query(Post);
query.descending('createdAt');
query.find().then(function(results) {
res.render('posts/index', {
posts: results
});
},
function() {
res.send(500, 'Failed loading posts');
});
};
// Display a form for creating a new post.
exports.new = function(req, res) {
res.render('posts/new', {});
};
Pass the app reference to the post controller, and add the routes from there

Resources