Reputation: 33
CORS: A very common issue that most of the developers face when they hit a rest service from another domain and so do I.
I get this error :
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
Below is the jsp snippet.
<html>
<head>
<meta content="text/html; charset=utf-8">
<title>AJAX JSON SAMPLE</title>
<script type="application/javascript">
function load()
{
var url = "https://samplewebapp1.herokuapp.com/rest/json/get";//use any url that have json data
var request;
if(window.XMLHttpRequest){
request=new XMLHttpRequest();//for Chrome, mozilla etc
}
else if(window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");//for IE only
}
request.onreadystatechange = function(){
if (request.readyState == 4 )
{
var jsonObj = JSON.parse(request.responseText);//JSON.parse() returns JSON object
document.getElementById("appName").innerHTML = jsonObj.appName;
document.getElementById("language").innerHTML = jsonObj.language;
}
}
request.open("GET", url, true);
request.send();
}
</script>
</head>
<body>
appName:
<span id="appName"></span>
<br /> language:
<span id="language"></span>
<br />
<button type="button" onclick="load()">Load Information</button>
</body>
</html>
Below is the rest service implementation of that service.
`package com.heroku.rest;
import java.util.Date;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.heroku.model.Heroku;
@Path("/json")
public class HerokuRestService {
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public Heroku getTrackInJSON() {
return new Heroku("My First Heroku", "Java", new Date().toString());
} }`
What am i missing.?
Upvotes: 3
Views: 30044
Reputation: 124
You are trying to do a XmlHttpRequest to some other domain. You could simply use CORS to tell your browser to allow it. (It's completely browser specific due to some security reasons).
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US use this extension to allow access to no 'access-control-allow-origin' header request.
Or, you could manually configure CORS as well. Like described here https://www.html5rocks.com/en/tutorials/cors/
Upvotes: 1