Magento2 – How to Get Base URL from a JS File

base-urljavascriptmagento2module

I want to retrieve a base URL and append it with my module controller link from a JS file, so it's impossible to use a block to get the base URL. So far I've done this:

define([
   'jquery',
   'mage/url'
], function ($,url) { 

  var linkUrl = url.build('namespace_module/regions/index');
  console.log(linkUrl);
});

But I only got this result:

namespace_module/regions/index

Best Answer

define([
   'jquery',
   'mage/url'
], function ($,url) { 

  var linkUrl = url.build('frontname/regions/index');
  console.log(linkUrl);
});

Where frontname is your routes.xml file frontname.

You have to pass your frontname from routes.xml file instead of module name(namespace_module)

You can lookup your routes.xml file from app/code/Namespace/Module/etc/frontend/routes.xml

Related Topic