2

I am trying to send token on server using Ajax post request. This is basic html code running separately http://localhost:56471

$.ajax({
      type: 'POST',
      url: 'http://localhost:8080/sometoken' ,
      contentType: 'application/octet-stream; charset=utf-8',
      success: function(result) {
        // Handle or verify the server response.
          console.log("Result is: " + result);
      },
      processData: false,
      data: sometoken,
    });

My servlet app running on port 8080 trying to get token

public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException {
       String name=req.getParameter("token");
       response.setContentType("text/plain");
       response.setCharacterEncoding("UTF-8");
}

I am totally new to servlet. This is my first servlet. Error I get when ajax post is called XMLHttpRequest cannot load http://localhost:8080/sometoken. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:56471' is therefore not allowed access.

Can anyone please help me how I can this post request without error?

Thanks

user557657
  • 856
  • 1
  • 12
  • 35

1 Answers1

0

The problem in your case is the famous CORS (CROSS ORIGIN RESOURCE SHARING)

Cross-Domain, or cross-origin, AJAX requests are requests from a web page hosted on domain X to a server hosted on domain Y. As a safety precaution the browser prohibits this, unless the server says it's okay by sending the appropriate Http-headers (http://codepen.io/nicohaemhouts/post/cross-domain-ajax-with-tomcat-and-jquery).

As i understand, since you are the owner of both domains, then you can overcome this by simply enabling the cross domain exchange of information. This can be done by modifying the default behavior of the server you are requesting information from.

This can be done by modifying the web.xml and apply a filter that will simply allow this exchange:

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Assuming that you use Tomcat, other configurations are also available. Just see tomcats api

MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125