www.jensolsson.se
www.jensolsson.se

Reputation: 3073

restify.serveStatic not handling default document

I have a REST application written in javascript based on node and the restify plugin.

I have some REST functions set up:

var server = restify.createServer();
server.use(restify.bodyParser());
server.get('/person/:id', getPerson);
server.get('/group/:id', getGroup); 

I also want to serve some static files and I want them to be accessible from http://server/admin/

I have the following source code to make this possible:

server.get(/\/admin\/?.*/, restify.serveStatic({directory: '/var/www/node/app/html/', default: 'index.html'}));

/var/www/node/app/html/ contains a folder named "admin" and this folder contains a file named index.html Below is the folder structure:

html
└── admin
    ├── img
    │   ├── icon1.png
    │   ├── icon2.png
    │   ├── icon3.png
    └── index.html

If I try to visit http://server/admin/ I will get the following error:

{"code":"ResourceNotFound","message":"/admin/"}

The following path works fine http://server/admin/index.html. and I can also access http://server/admin/img/icon1.png etc.

So to sum it up, there seem to be an issue with the default setting of serveStatic.

I use restify 2.6.0 and I am aware of that there are newer versions available, but since some other things changed on later Restify versions I am not able to upgrade at the moment.

Upvotes: 1

Views: 857

Answers (1)

jexact
jexact

Reputation: 541

Try this workaround:

var restify = require("restify");

var server = restify.createServer(); // create server

var defaultDoc = "index.html"; // your default document

server.pre(restify.pre.sanitizePath()); // sanitize paths (e.g. "/admin/" will result in "/admin")
server.use(restify.bodyParser()); // body parser

// route "/admin" requests to "/admin/index.html"
server.use(function(req, res, next){
    req.url = (req.url === "/admin" ? "/admin/" + defaultDoc : req.url);
    return next();
});

// your routes...
server.get("/person/:id", getPerson);
server.get("/group/:id", getGroup); 

// route for static files
server.get(/\/admin\/?.*/, restify.serveStatic({
    "default":   defaultDoc,
    "directory": "/var/www/node/app/html"
}));

server.listen(8080, "0.0.0.0");

Upvotes: 1

Related Questions