Cross-origin request support

I have my module running Spring Securty 4 and I want to make a Cross-Origin AJAX Call to my module /token endpoint to issue a new token.

options = {
            url: tokenUri,
            type: 'POST',
            data: data,
            headers: {
                    "Authorization": "Basic dGVzdDM6YWQ= "
                },
            crossDomain: true
        };
$.ajax(options).done(function(res){`

This is the request I am making to my module localhost:8080/openmrs/ws/oauth/token endpoint.

And this is the exact ERROR I get XMLHttpRequest cannot load localhost:8080/openmrs/ws/oauth/token. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

On looking online, I found an easy solution to the problem:

<mvc:cors>
		<mvc:mapping path="/api/**"
					allowed-origins="http://domain1.com, http://domain2.com"
					allowed-methods="GET, PUT"
					allowed-headers="header1, header2, header3"
					exposed-headers="header1, header2" allow-credentials="false"
					max-age="123" />
		<mvc:mapping path="/resources/**" allowed-origins="http://domain1.com" />
	</mvc:cors>

However, this solution is since Spring MVC version 4.2 and above and OpenMRS uses 4.1.4.RELEASE

Any help or suggestion is appreciated. My ajax request -> https://pastebin.com/DYTkDKPS My module -> https://github.com/mavrk/openmrs-module-oauth2-prototype/tree/oauth2-pure-rest

So, I am assuming you are making the request from your local js or html file (i.e. the url from where you are making request might look like file://C:/ ). Instead, you should host that file on a local server to avoid CORS at development time. If you have python>3 installed, you can easily host a folder locally using

python -m http.server 8080 (https://docs.python.org/3.6/library/http.server.html?highlight=http%20server#module-http.server)

Or IDE’s like WebStorm can automatically do it for you too

https://blog.jetbrains.com/webstorm/2013/03/built-in-server-in-webstorm-6/

@mavrk When I faced this issue. I used this plugin. Enabling it lets me run it locally :slight_smile:

Thank you @maany @reubenv. I am running my html files from localhost i.e. Apache So my files are hosted on localhost:\ and module on localhost:8080\ (Tomcat). I introduced a CORS filter to allow all headers for my module so localhost:8080openmrs\ws is covered by that filter.

This is the error I am getting as of now,

And I’ve also enabled the CORS chrome plugin you mentioned.

1 Like

Running the application as well as the module on Tomcat works! (No more cross-origin)

@reubenv We are developers, So we can use that plugin to enable the CORS with our environment. But when another one tries to use this module, he may face this problem again (possibly he may not have that plugin).

So better way is enable CORS on the server side :slight_smile:

2 Likes

Makes sense, couldn’t agree more :smile:

1 Like