title: No Access-Control-Allow-Origin header is present on the requested resource
body: <p>I want to access information from same domain but with different port number, To allow this I am adding <code>Access-Control-Allow-Origin</code> with the response header.</p>
  
  <p><strong>Servlet Code:</strong>(present on www.example.com:PORT_NUMBER)</p>
  
  <pre><code>String json = new Gson().toJson(list);
  response.setContentType("application/json");
  response.setCharacterEncoding("UTF-8");
  response.setHeader("Access-Control-Allow-Origin", "*");//cross domain request/CORS
  response.getWriter().write(json);
  </code></pre>
  
  <p><strong>jQuery code:</strong>(present on www.example.com)</p>
  
  <pre><code>$.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'}).done(function(data)
  {
      alert(data);
  });
  </code></pre>
  
  <p>Several times I am getting this error(in console):</p>
  
  <pre><code>XMLHttpRequest cannot load 'http://www.example.com:PORT_NUMBER/MYSERVLET'
  No 'Access-Control-Allow-Origin' header is present on the requested resource.
  </code></pre>
  
  <p>This error mostly occures first time when <code>$.post</code> gets executed. Second time it allows.</p>
  
  <p>My question is that is there missing in <code>servlet</code> or in <code>jQuery</code> code?</p>
  
  <p>Any suggestion will be appreciated.</p>
  
  <p><strong>Update1</strong></p>
  
  <p>I have changed:</p>
  
  <pre><code>response.setHeader("Access-Control-Allow-Origin", "*");
  </code></pre>
  
  <p>To:</p>
  
  <pre><code>response.setHeader("Access-Control-Allow-Origin", "http://www.example.com");
  </code></pre>
  
  <p>Then I am getting this error in console:</p>
  
  <pre><code>XMLHttpRequest cannot load http://www.example.com:PORT_NUMBER/MyServletName
  The 'Access-Control-Allow-Origin' whitelists only 'http://www.example.com'
  Origin 'http://www.example.com' is not in the list,
  and is therefore not allowed access.
  </code></pre>
  
  <p>[Note: whitelist and origin are same, but still it gives error. It works sometimes, and gives above error sometimes.]</p>
  
  <p>Let me know if you need anymore information.</p>