Cody
Cody

Reputation: 10015

SailsJS Does Not Invoke Controller Action When URL Ends With File Extension

SailsJS Does Not Invoke Controller Action When URL Ends With File Extension

I have a route set up to handle requests to an image...

./config/routes.js

module.exports.routes = {
  ...,
  '/api/v1/uploads/products/:productId/:filename': 'image',
};

I have that controller/action in my controllers. However, I get a 404 when visiting the url...

http:localhost:1337/api/v1/uploads/products/87a5sdfaas7/as78a8sb8h7.png

However, when I visit...

http:localhost:1337/api/v1/uploads/products/87a5sdfaas7/test

... I do hit my controller. But if I visit...

http:localhost:1337/api/v1/uploads/products/87a5sdfaas7/test.png

...then I get a 404 again.

It seems that Sails bails out of any routing as soon as it encounters anything that looks like a file. I believe this Sails, itself, and not Express as I believe I've used routes like this in ExpressJS before.

Is there a way to explicitly tell Sails "This may look like a file but DON'T abandon the router and still hit my controller for this"? How do you get around this?

Upvotes: 0

Views: 15

Answers (2)

Kelvin Omereshone
Kelvin Omereshone

Reputation: 816

So here is what's happening...

By default Sails has two types of routes: automatic(implicit) and custom(explicit) routes which are the ones you are setting in config/routes.js

Automatic routes are made for things like file serving and for the Blueprint API in Sails.

From your code, it seems you are hitting an automatic route to serve files since your URL ends with a file extension Sails is assuming you are making a request to an asset in your .tmp/public but such assets doesn't exit there hence the 404.

You can opt-out of this behaviour on a per route basis by using the skipAsset option like so:

module.exports.routes = {
 '/api/v1/uploads/products/:productId/:filename/image': {
   action: 'image',
   skipAssets: true // Sails won't try to match this request to an asset
}
}

Hopefully this help, you can check the docs for the skipAssets option as well as other route options.

I hope this helps.

Upvotes: 0

Cody
Cody

Reputation: 10015

A Workaround

As I was writing the question, I came up with a useful workaround. Here's how I redefined my route...

./config/routes.js

module.exports.routes = {
  ...,
  '/api/v1/uploads/products/:productId/:filename/image': 'image',
};

That's basically it. Now Sails doesn't abandon the router. Hope that helps!

Upvotes: 0

Related Questions