Sails.js regex routes - javascript

I am building a simple sails.js project and implementing the front end with backbone.
Ideally I want a single route to the one index page in which my backbone app is served.
'/*': {
view: 'home/index'
}
This is great, so any URL now goes to the homepage. Except now, all the routes to any assets (.js, .css, .html, .jpg) do not work anymore.
I can see this comment in the config.routes.js:
// NOTE:
// You'll still want to allow requests through to the static assets,
// so we need to set up this route to ignore URLs that have a trailing ".":
// (e.g. your javascript, CSS, and image files)
'get /*(^.*)': 'UserController.profile'
But it doesn't make any sense to me. How do I ignore routes with a file extensions.
I have also prefixed all my CRUD url's with 'api', localhost:1337/api/controller/ so a regex route to exclude forwarding those would also be required. I cannot find any information on how to do this anywhere.
I must be missing something fundamental here.
Thanks!

You can use the skipAssets and skipRegex flags. This will not step on your static assets and will not block your api urls starting with /api. I use this with sails.js and angular in html5Mode.
"get *":{
controller:"PagesController",
action:"index",
skipAssets: true,
skipRegex: /^\/api\/.*$/
}

I think this is a bug but I found a workaround solution.
'get /[^.?]+?': 'UserController.profile'
or you can use other one. only /user and /profile will exec UserController.profile. static directory still work great.
'get /:action( user | profile)': 'UserController.profile'

Related

How would I add URL subsections/subpages?

How would I add things like this:
/page/sub-section
ex: https://url.com/account/notifications
In terms of a static site, each slash represents a single directory on your web server.
/page/sub-section
Would mean you have the
/ the root directory
/page a folder called page
/sub-section another folder called sub-section
In the last folder, you would then have your index file, which will be loaded once visiting the URL. For example index.html.
In terms of web development this is named routing and all the big web frameworks come with own modules for routing. Here you don't have to create directories as described above, instead these frameworks will handle the request and route it internally to find the right content and display it for that route.

Match all routes with or without .html extension, except for static assets

I'm trying to set up a generic handler for every request that is not something like an image or favicon or anything like that. For example I want this handler to handle /index, /index.html, /user/123, etc., but not /favicon.ico, /sunflower.png, /images/starfish.png, etc.
This is currently what I have
app.get('/:name', (req, res) => {
res.render(req.params.name)
})
But this is of course matching /favicon.ico, and every other url that I don't want it to match. It also doesn't match .html extensions. Is there a clean solution out there for this situation?
The best solution in a production environment to serve static assets, like the images you have listed, is to place a front facing proxy (eg: nginx) in front of Express and configure it accordingly.
That way, request for static assets are offloaded to the proxy, and never reach Express. Express is best for serving dynamic content asynchronously, do not use it for serving files.

How to replace post ID with url slug

I have a DB table that saves my title as a slug (ie: this-is-my-title-slug) but I have no clue how to use it in the url.
Example ofor current url http://www.example.com/post.php?id=102
What I want is
http://www.example.com/this-is-a-slug.
You're looking at SEO urls. And a slug is something you would use as a name of an article on www.example.com/articles/article-title-slug for instance, what you probably mean is a permalinks which basically are SEO urls.
If you're running an apache server with PHP and you have a vhost setup then you can use that vhost to allow url rewriting (Apache mod_rewrite).
This allows you to place a file called .htaccess in the webroot of your project (e.g. same directory as root index.php file), within this file you can set up rules that allow such rewriting. What often happens is that you rewrite everything to the root index.php file and you capture the URI and parse the parameters by splitting it on the forward slash (/) character. This is basically a router idea.
The advantage of parsing the URI yourself is that you don't really have to do much in the .htaccess file which is much more complex to handle than building a router in PHP itself as well.
A good example of a .htaccess file can be found on this SO answer
about how to get going with that. There are also plenty of other tutorials to get started with this other than that answer.
DigitalOcean - How to use the .htaccess file
TutsPlus - The ultimate guide to .htaccess
It's been a while since I've done it myself but if you have questions, just ask them and I'll see if I can help but anyways, this should point you in the right direction.

Javascript React Single Page Application + Amazon S3: Permalinks issue

I am using an S3 bucket as static web solution to host a single page React application.
The react application works fine when I hit the root domain s3-bucket.amazon.com and the HTML5 history api works fine every time I click on a link the new url looks fine: _http://s3-bucket.amazon.com/entities/entity_id_
The problem happens when I use permalinks to access the application. Let's assume I am typing the same url (_http://s3-bucket.amazon.com/entities/entity_id_) in the browser I will get the following error from Amazon S3:
404 Not Found
Code: NoSuchKey
Message: The specified key does not exist.
Key: users
RequestId: 3A4B65F49D07B42C
HostId: j2KCK4tvw9DVQzOHaViZPwT7+piVFfVT3lRs2pr2knhdKag7mROEfqPRLUHGeD/TZoFJBI4/maA=
Is it possible to make Amazon S3 to work nicely with permalinks and HTML5 history api? Maybe it can act as proxy?
Thank you
Solution using AWS CloudFront:
Step 1: Go to CloudFront
Click on distribution id
Go to the Error page tab
Click on Create Custom Error Response
Step 2: Fill the form as
HTTP Error Code: 404
TTL: 0
Custom Error Response: Yes
Response Page Path: /index.html
HTTP Response Code: 200
source: https://medium.com/#nikhilkapoor17/deployment-of-spa-without-location-strategy-61a190a11dfc
Sadly S3 does not support the wildcard routing required for single page apps (basically you want everything after the host in the url to serve index.html, but preserve the route.
So www.blah.com/hello/world would actually serve www.blah.com/index.html but pass the route to the single page app.
The good news is you can do this with a CDN such as Fastly (Varnish) in front of S3. Setting up a rule such as:
if(req.url.ext == "" ) {
set req.url = "/index.html";
}
This will redirect all non asset requests (anything without a file extension) to index.html on the domain.
I have no experience running SPA on Amazon S3, but this seems to be a problem of url-rewriting.
It is one thing do have the history (html5) api rewrite your url when running your application / site.
But allowing rewritten urls to be accessible when refreshing or cold-surfing to your site definitely needs url-rewriting on a server level.
I'm thinking web.confg (IIS), .htaccess (Apache) or nginx site configuration.
It seems the same question already got asked some time ago: https://serverfault.com/questions/650704/url-rewriting-in-amazon-s3
Specify the same name for the index and error files on "Static website hosting" properties. See linked image 1.
Old question but simplest way would be to use hash routing. So instead of mydomain.com/somepage/subpage it would be mydomain.com/#/somepage/subpage

How can I serve a default image file in express.js?

In my express.js project, I am serving up the dist folder of my project like so:
server.use(express.static('dist'))
In my dist folder, I have an img/fileicons folder that contains PNG files that represent various file types, e.g. 'txt.png', 'html.png', 'pdf.png', etc. In case an image doesn't exist for a given file type, I want to set up a default route that would serve up 'blank.png' with a generic file image. For example, if the URL '/img/fileicons/[doesn't exist].png' is hit, then 'blank.png' is returned. However, if I navigate to another path that doesn't exist, like '/html/[doesn't exist].html', then I don't want the 'blank.png' file served up.
How can I set up my express.js routing to accommodate this need?
At the bottom of the routes, make a default one:
app.get('/dist/img/fileicons/*', function(req, res) {
res.sendfile('path/to/blank.png')
});
All you need to do is put some middleware at the bottom of your stack and use res.sendfile(). Don't forget to use res.statusCode(404) so that crawlers don't think they're hitting a real resource.

Categories