i'm having major issue routing in express.
in project, there folder /public
.
inside /folder
have other folders like
- public |- user |- common
initially, way pages served node.js server through res.sendfile(../..)
. problem .js
files , .css
files did not know go.
so added
app.use('/', express.static(__dirname + '/public'));
but problem is, if try visit /user
happens is, static version of index.html
file in folder returned, , route defined in node app ignored!
this route - , importantly auth middleware never touched!
how reconcile need serve files static folder, may have routes of same name want control more closely?
app.use('/user', userauth, userroutes);
assuming /user
sort of api don't think express.static intended used way. think best solution use different routes. add /api/ beginning of routes or make sure static files organized under /css, /js, /partials, etc.
if absolutely must support /user static files , api calls need ditch express.static , use accept header custom middleware determines browser asking for. depending on scenario may complicated support variables. simple example this:
app.use(function(req, res, next){ // check accept header make sure json request if(req.accepts('application/json') && !req.accepts('html')) { // json request forward request on next middleware(eventually hitting route) return next(); } // not json request lets serve file if exists... // todo use req.path check if file exists - if not 404 - need map paths // /users check /users/index.html if need support var fileexists = false; return fileexists ? res.sendfile('...') || res.status(404).send('not found'); });
you have make sure when client calls /users
sets accept header application/json
. client side frameworks have way ajax requests.
Comments
Post a Comment