How to get the base or root url in sailsjs? How to get the base or root url in sailsjs? express express

How to get the base or root url in sailsjs?


Sails.js is based on Express, so from within your action you can do the following:

var protocol = req.connection.encrypted?'https':'http';var baseUrl = protocol + '://' + req.headers.host + '/';


Just to give an updated answer for anyone that finds this page...

In Sails v0.10 you can access it through req.baseUrl or sails.getBaseurl() in your views.

Answer taken from: How to get current domain address in sails.js


A couple other options available... sails.config.appPath or require('path').resolve('.') and both will return a path from your app's drive to the app root. Caveat is local development as C:\websites\mywebsite\remote is not very useful and any loaded asset will be blocked by the browser.

This source uses the require.resolve() function to calculate the absolute path of appPath and appending assets/images.

req.file('avatar').upload({  dirname: require('path').resolve(sails.config.appPath, 'assets/images')},function (err, uploadedFiles) {  if (err) return res.negotiate(err);  return res.json({    message: uploadedFiles.length + ' file(s) uploaded successfully!'  });});

In the above example you could change 'assets/images' to '../assets/images' to store file uploads below the root of your website - if you are into hiding your stuff!

Here is a good article about require.resolve().