问题
I am hosting a widget on another domain than the site in which I am embedding the widget.
The dashboard.js loads fine, but the HTML template gets,
XMLHttpRequest cannot load http://192.168.2.72:8081/widgets/templates/dashboard.html. Origin http://192.168.2.72:8080 is not allowed by Access-Control-Allow-Origin.
The url to the template is correct, so I can only assume this is a cross domain error. In the widget, the template is referred to like:
templatePath: dojo.moduleUrl("monitor/dashboard", "../templates/dashboard.html"),
This all works when it's a local widget. Is there anyway to get dojo to load the HTML template in better way?
The way I have defined loader,
<script data-dojo-config="async: 0, dojoBlankHtmlUrl: '/blank.html', parseOnLoad:true,
packages: [
{name: 'monitor', location: 'http://192.168.2.72:8081' + '/widgets'},
]"
src="/media/scripts/dojo/dojo/dojo.js"></script>
回答1:
Well, there are several ways to solve it.
The first solution is a serverside solution by using CORS (Cross-origin resource sharing). If you can set the CORS headers like:
Access-Control-Allow-Origin: *
Your browser will detect this and will allow the XMLHttpRequest.
While this solution is probably the best, you could also use some alternatives, for example by using JSONP (for example with dojo/request/script
). However, using JSONP also means that you cannot use a plain HTML template, but you have to convert your HTML template to a JavaScript string.
If you then use the templateString
property, you can then pass the template as a string, in stead of specifying the path.
The templateString
property also allows you to build your template, if you can build your template as a JavaScript string, then you could build your template, for example by using Grunt and the grunt-html-convert task.
You might be able to do a similar thing with the Dojo build system by using depsScan. This build transform should scan modules and convert legacy code to AMD and it should also look for things like dojo.cache()
, dojo.moduleUrl()
and templatePath
and convert it to templateString
.
Look at the documentation for more info.
the last (and also pretty common) solution is to use a reverse proxy. If you have to host your HTML templates on a different domain, you can still define a reverse proxy in your HTTP server and redirect certain calls to a different domain, for example (Apache 2):
ProxyPass /templates http://other-domain.com
ProxyPassReverse /templates http://other-domain.com
This allows you to go to /templates/my-template.html
, which will be redirected to http://other-domain.com/my-template.html
.
来源:https://stackoverflow.com/questions/25239453/cross-domain-loading-of-widget-template