Message Boards

XMLHttpRequest cannot load Origin null is not allowed by Access-Control-All

thumbnail
Bolat Kazybayev, modified 10 Years ago.

XMLHttpRequest cannot load Origin null is not allowed by Access-Control-All

New Member Posts: 5 Join Date: 8/23/12 Recent Posts
Hi there,

I have an index.html file on a client machine which invokes Servlet using jQuery's get method.


			
		<meta charset="utf-8">
		<title>Get Cookies</title>
		<script src="jquery-1.9.1.min.js"></script>
		<script>
			$(document).ready(function() {
				$("button").click(function() {								
		    		$.get("http://localhost:8080/SimpleServletProject/GetCookiesServlet", function(responseJson) {
		      			var $ul = $('<ul>').appendTo($('#somediv')); // Create HTML <ul> element and append it to HTML DOM element with ID "somediv".
			            $.each(responseJson, function(index, item) { // Iterate over the JSON array.
			                $('<li>').text(item).appendTo($ul);      // Create HTML <li> element, set its text content with currently iterated item and append it to the <ul>.
			            });
		    		});				  		
				});
			});
		</script>
	
					
		<button>Send an HTTP GET request to a page and get the result back</button>
		<div id="somediv"></div>
	


My Servlet:

@WebServlet(description = "This servlet gets and decrypts userId from Cookie", urlPatterns = { "/GetCookiesServlet" })
public class GetCookiesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		response.setContentType("application/json");
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();				
		Cookie[] cookies = request.getCookies();
		String userId = null;
		String password = null;
		String companyId = null;
		for(Cookie c : cookies) {
			if ("COMPANY_ID".equals(c.getName())) {
				companyId = c.getValue();
			} else if ("ID".equals(c.getName())) {
				userId = hexStringToStringByAscii(c.getValue());
			} else if ("PASSWORD".equals(c.getName())) {
				password = hexStringToStringByAscii(c.getValue());
			}
		}
		
		if (userId != null &amp;&amp; password != null &amp;&amp; companyId != null) {
			try {				
				KeyValuePair kvp = UserLocalServiceUtil.decryptUserId(Long.parseLong(companyId), userId, password);				
				List<string> list = new ArrayList<string>();				
			        list.add(kvp.getKey());	    
				String json = new Gson().toJson(list);		
				writer.write(json);		
				writer.close();
			} catch (NumberFormatException e) {				
				e.printStackTrace();
			} catch (PortalException e) {
				e.printStackTrace();
			} catch (SystemException e) {
				e.printStackTrace();
			}
		}
	}
	
	public String hexStringToStringByAscii(String hexString) {
		byte[] bytes = new byte[hexString.length()/2];
		for (int i = 0; i &lt; hexString.length() / 2; i++) {
			String oneHexa = hexString.substring(i * 2, i * 2 + 2);
			bytes[i] = Byte.parseByte(oneHexa, 16);
		}
		try {
			return new String(bytes, "ASCII");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
	
}
</string></string>

When I try to invoke the Servlet, Google Chrome return me an error: XMLHttpRequest cannot load http://localhost:8080/SimpleServletProject/GetCookiesServlet. Origin null is not allowed by Access-Control-Allow-Origin. Though I make this in the Servlet:

response.setHeader("Access-Control-Allow-Origin", "*");


By the way, when I do not use UserLocalServiceUtil service and deploy the Servlet on the separate Tomcat my html file successfully invokes the Servlet and gets the response from the Servlet.
Any ideas how to solve this problem are welcome.
Gever Wills, modified 3 Years ago.

RE: XMLHttpRequest cannot load Origin null is not allowed by Access-Control

New Member Post: 1 Join Date: 9/28/20 Recent Posts
This is happening because of the CORS (Cross Origin Resource Sharing) error. This error occurs when you try to access a domain/resource from another domain. You cannot issue requests through the XMLHttpRequest to other domains or subdomains. For example, if you are doing something like writing HTML and Javascript in a code editor on your personal computer, and testing the output in your browser, you might probably get error messages about Cross Origin Requests .
JSONP ( JSON with Padding ) is a method commonly used to bypass the cross-domain policies in web browsers. 
If this is for local development and you are using Chrome , you need to run Chrome with a couple of arguments to relax security like this:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files --disable-web-security
If you need to enable CORS on the server in case of localhost, you need to have the following on request header.
Access-Control-Allow-Origin: http://localhost:9999
The other easy way out, would be to create a proxy on your local server, which gets the remote request and then just forwards it back to your javascript.
http://net-informations.com/js/err/xml.htm