I need to make routing flexible for slashes, for example
app.get('/home/pages')
router must handle
////home///pages
/home/pages////
etc...
requests.
Currently I have one idea to implement this, but for that I need to know how to reroute request via middleware,
If you can answer this question or suggest something else I will be grateful to you.
Also please don't suggest using regex for defining routers, because project is already done and there is a lot of already defined routes.
You need to rewrite url in a middleware:
var express = require('express');
var app = express();
app.use(function (req, res, next) {
req.url = req.url.replace(/\/+/g, '/');
next();
});
app.get('/home/pages', function (req, res) {
res.send('some pages');
});
app.listen(3000);
Related
I am trying to add a validation middleware in order to protect my server data. When I get request (http://localhost:3000/filepath) the static route without the middleware:
app.use(express.static('data'));
I get a status 200 OK. But when I tried to get request the same route, but this time using a simple middleware as recommended in this other question (Is it possible to use validation with express static routes?)
var staticMiddleware = function(req, res, next){
console.log("middleware")
next();
}
app.use(staticMiddleware, express.static('data'));
I`ve got a status 404 not found.
How can I add another middleware to app.use before the express.static middleware?
You need to add them seperately.
app.use(express.static('data'));
var staticMiddleware = function(req, res, next){
console.log("middleware")
next();
}
app.use(staticMiddleware );
I'm creating an app using node, express, and have a passport authorization middleware implemented for all routes-. I am following a highly modular approach to build my app. I try to exclude specific APIs from authentication when I include them above the authorization middleware. But when I include app.use('/', require('./api/search/index')); above the authorization middleware, APIs beneath stop working.
Criticism and suggestion are all welcome for this approach and what can I do to resolve this problem.
I don't want to include route middleware in each route like this
route.get('/example', auth.middleware(), function (req, res) {
})
Below is my app approach with single authorization middleware for all routes
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var auth = require("./auth.js")();
app.use(auth.initialize());
//Excluding the search API from Authentication,
app.use('/', require('./api/search/index'));
//Middleware for all APIs and require Auth headers for authrization access
app.use(auth.authenticate(), function (req, res, next) {
if (req.headers.authorization && req.user) {
var parted = req.headers.authorization.split(' ');
if (parted.length === 2) {
console.log(req.user);
next();
} else {
return res.status(403).send({
success: false,
msg: 'Unauthorized.'
});
}
} else {
return res.status(503).send({
success: false,
msg: 'Bad Request'
});
}
});
//Join routers
app.use('/', require('./api/users/index'));
app.use('/', require('./api/product/index'))
app.use('/', require('./api/company/index'))
There are a million ways you can do this. What you can do is this:
app.use('/', require('./api/search/index'));
app.use('/', auth.authenticate(), require('./api/users/index'));
app.use('/', auth.authenticate(), require('./api/product/index'))
app.use('/', auth.authenticate(), require('./api/company/index'))
This way, the auth.authenticate() middleware will be applied to every child route you are requiring. And you leave the index without anything. This gives you a more granular control of where you apply the auth middleware, without having to apply it to every single route. You can take this to another level and group several routes inside a /admin/ and apply the middleware only once. Your imagination is the limit.
You can block your routes together using express.Router. For instance, you could have a route called "/api/secure" and then create a router for that route and group all secure routes there. and then have another for unsecured routes'
Express Router Docs
I try to make a Single Page App on Express. The main problem is that I use Express route feature, that re-renders the view each time the URL changes and GET request gets to server. I have a rather usual code like:
// Express routes
var routes = {
index: require('./routes/home')
};
// use routes
app.use('/', routes.index);
//home.js
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
res.render('home', {title: "ITEF"});
});
router.get('/about', function (req, res, next) {
res.render('home', {title: "ITEF"});
});
Is there any way to make router ignore URL changes and let the front-side app be as it is? The plan is to buld all UX logic according to URLs, but without countless re-rendering.
Found out that it's rather easy with pushState HTML5 feature:
window.history.pushState('object or string', 'Title', '/about');
Details described in a good article here.
I little bit late for answering, but I managed to do what you asked using a library called Finch.js.
So, when I want to call another URL in my Single Page Application, I use Finch.navigate('/profile'). The URL will change, and there will be no call to the node server.
Finch.route("/profile", function () {
main.viewModel(new app.model());
});
Finch.listen();
Finch.navigate('/profile');
You can learn more about the library here FINCH
I am trying to prepend a NodeJS request through express to include /api/v1. If I make an addition like to to my server.js file:
app.all('/Employees', require('./routes/Employees'));
I am able to go forward to localhost/Employees and get the proper response (it comes back from the javascript I have written in ./routes/Employees)
If I add /api/v1/ to the beginning of the app.all call, like so:
app.all('/api/*', requireAuthentication);
I am not able to go forward to localhost/api/v1/Employees. The express manual even has an explicit note about this:
Another example is white-listed "global" functionality. The example is much like before, however it only restricts paths that start with "/api":
http://expressjs.com/api.html#app.all
Any help would be greatly appreciated.
Your app gets confused whenever request is received at /api/* -- it doesn't know where to go and what to do now.
If you want to prefix /api/v1 for your requests, you can do it with couple of ways - Choose what best suits your in your case:
Mountpath way -
var express = require('express'),
app = express(),
api = express();
api.all('/employees', function(req, res){
console.log("url :: " + api.mountpath);
res.send('hit at employess');
});
//you can do this here fo v(n)
app.use('/api/v1', api);
app.listen(3000);
other way -
var express = require('express');
var app = express();
app.all('/employees', function(req, res){
res.send('/employe');
});
app.use('/api/v1', function(req, res, next){
res.redirect(req.path);
});
app.listen(3000);
Happy Helping!
Nowadays i am using https://github.com/baugarten/node-restful wich helpme to work in an API, the question is?
I am working in Express framework, are there a way to protect the "GET" request from other site to mine.
I use the CSRF from express but only work by POST,PUT,DELETE methods with a message of FOrbidden 403 when treat make anithing since curl in console but if I make a curl toward a Get method curl localhost:3000/posts that giveme an array with all the posts.
app.use(express.csrf());
app.use(function(req, res, next){
res.locals.token = req.session._csrf;
next();
});
app.use(app.router);
What you advice me? are there other modules to work an Api better? How can protect an Api in nodejs? What are the best practices that a haver to learn?
Thanks by your Help.
Try Express middleware which is designed to do so. For example:
var express = require('express');
var app = express();
// simple middle ware to protect your URI
app.use(function(req, res, next){
if (req.method == 'GET') {
if (!req.locale.token) { res.send(403); } // custom to fit your policy
else if (req.protocol !== "https") {res.redirect("your-secure-url");}
else { next(); }
}
});