The issue of Access-Control-Allow-Origin not functioning properly when using Ajax for a POST request

I am encountering an issue with the header "Access-control-allow-origin" when making a request using the following code:

<script type='text/javascript'>
function save() {
          $.ajax(
        {
       type: 'POST',
       url: "...",                
       contentType: 'application/json',
       data: '{"cuspp":"228061JGLIR5", "userWeb":"46689"}',
       success: function (data) {
               console.log("It Works");
               console.log (data);
               if (data.codigo==0){
                   console.log(data.mensaje);
              }else{
                  console.log(data.message);

             }
           },
       error: function (jqXHR, textStatus, errorThrown) {
                   console.log("error");
            }
        });
}
</script>

The response is generated by a Java client as follows:

@POST
@Path("/pcnct020")
@ApiOperation(value = "Save events.", notes = "PCNCT020", responseClass = 
"data.Answer")
public Response saveEvents(
   @ApiParam(value="Structure of Event", required = false) Evento event) {     


   Answer<Result> answer = Validator.validate(event);

   if (answer.esOK()) {

       int size = event.textDetail.length();

       int count = size / 60;

       String comment =  event.textDetail;
       int secuence = 0;

       for (int j = 0; j <= count; j++) {
           evento.secuence = secuence;
           String newString;

           if (j == 0) {                                           
               if (size < 60) {                                    
                   newString = comment.substring(j * 60);

               } else {                                            
                   newString = comment.substring(j * 60,
                           (j * 60) + 60);
               }

           } else if (j == count) {                            
               newString = comment.substring(j * 60);          
               if (newString.equals("")) {                     
                   break;
               }

           } else {
               newString = comment.substring(j * 60,
                       (j * 60) + 60);
               if (newString.equals("")) {
                   break;
               }
           }
           event.textDetail = newString;   
           answer.setAnswer(event.saveEvent());
           secuence = Integer.parseInt(answer.ans.status);
       }

   }
   return Response
            .status(200)
            .header("Access-Control-Allow-Origin", "...")
            //.header("Access-Control-Allow-Credentials", "true")
            //.header("Access-Control-Allow-Headers", "Origin")
            //.header("Access-Control-Allow-Methods", "GET, POST, DELETE, 
               PUT, PATCH, HEAD, OPTIONS")
            //.header("Conten-Type","application/application/json")
            .entity(answer)
            .build();

}

Upon trying to access from the specified address, I encounter an error in the browser console related to the "Access-Control-Allow-Origin" header:

XMLHttpRequest cannot load . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access.

I have attempted adding additional headers following the comments in the Java response code with no success.

Your assistance would be greatly appreciated.

UPDATE:

  public void getService(){

        try {

         String urlWS = "Web Service Url";

         String url = urlWS;

         CloseableHttpClient httpclient = HttpClients.createDefault();

         HttpPost httpPost = new HttpPost(url);

         httpPost.setHeader("Content-type", "application/json");

         StringEntity params =new StringEntity("
         {\"cuspp\":\"228061JGLIR0\", \"usuarioWeb\":\"46683\");                                        


         httpPost.setEntity(params);


         CloseableHttpResponse response = 
         httpclient.execute(httpPost);

         System.out.println(response.getStatusLine());               

         System.out.println(response.getStatusLine().getStatusCode());

         if(response.getStatusLine().getStatusCode() == 200){
             BufferedReader brResponse = new BufferedReader(new 
             InputStreamReader(response.getEntity().getContent()));
             String responseText = "";
             String output = "";
             while ((output = brResponse.readLine()) != null) {
                        responseText += output;
             }
             System.out.println(responseText);


        }             

    } catch (Exception excepcion) {            
            System.out.println(excepcion.toString());
    }
    finally{

    }
}  

A Java client was created which functions correctly. While unsure why Ajax is not functioning properly, this demonstrates that the web service operates correctly and the issue lies within the client.

Warm regards.

In the interest of privacy, URLs have been omitted from the code.

Answer №1

To solve your issue, incorporate ContainerResponseFilter into your service;

public class Filter implements ContainerResponseFilter {

    @Override
    public ContainerResponse filter(ContainerRequest request,
            ContainerResponse response) {

        response.getHttpHeaders().add("Access-Control-Allow-Origin", "*");
        response.getHttpHeaders().add("Access-Control-Allow-Headers",
                "origin, content-type, accept, authorization, X-Request-With");
        response.getHttpHeaders().add("Access-Control-Allow-Credentials",
                "true");
        response.getHttpHeaders().add("Access-Control-Allow-Methods",
                "GET, POST, PUT, DELETE, HEAD");

        return response;
    }
}

Answer №2

In order to address the issue, I came up with a solution which involved creating a new class that implements the ContainerResponseFilter interface (com.sun.jersey.spi.container) using the provided code:

@Provider
public class SummerResponseFilter implements ContainerResponseFilter {

@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) 
{

    //BEGIN OT 10533 - PSC001
    String path = request.getPath();

    if(path.contains("pcnct020")){
        response.getHttpHeaders().add("Access-Control-Allow-Origin", "*");
        response.getHttpHeaders().add("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");
        response.getHttpHeaders().add("Access-Control-Allow-Headers","Content-Type");

    }

    //END OT 10533 - PSC001

    if (Logger.isDebugEnabled()) {
        Logger.debug("Finished processing URL [%s] %s", request.getMethod(), request.getRequestUri().toString());
    }
    if (Logger.isTraceEnabled()) {
        Logger.trace("Response - Headers    = [ %s ]", response.getHttpHeaders().toString());
        Logger.trace("Response - Status     = [ %d ]", response.getStatus());
    }
    Answer.clean();
    return response;
 }

}

Afterward, it is necessary to define the XML configuration as follows:

<init-param>
      <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
      <param-value>filter.SummerResponseFilter</param-value>
 </init-param>

This approach allowed me to successfully overcome my issue. Hopefully, it can be of assistance to others facing similar challenges.

I appreciate all the help provided.

Answer №3

This resource can provide you with a fundamental understanding of CORS.

In essence, a CORS error arises when your client from the domain www.example1.com* attempts to access an API hosted on www.example2.com. The browser triggers the CORS error as a security measure.

To address this issue, there are two possible solutions:

  1. On the backend server www.example2.com, enable CORS headers for all incoming requests (allowing requests with headers from other origins). Additionally, make sure to set CORS headers in your AJAX request. This way, the request will go from Client -> www.example2.com/post_url.

  2. Alternatively, I recommend this approach: From your client on www.example1.com, access an internal route www.example1.com/api/post_url and redirect all requests to /api to www.example2.com using NGINX or Apache server configuration. Consequently, the request flow will be Client -> www.example1.com/api/post_url -> www.example2.com/post_url.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using NextJS to pass a string from an input field to getStaticProps via context

I am a beginner in NextJS and React, so please forgive my lack of knowledge. I am trying to figure out how to pass the text input by users from an input field (inside Header) to the getStaticProps function of a specific page using the React context API. I ...

Is the 'Document' term not recognized within expressjs?

I'm having trouble implementing a query selector in an ExpressJS application and it's not working // search products router.post('/search', function(req, res) { var db = req.db; var elasticlunr = require(&apo ...

How can I address the issue of having multiple console logs within the

I am facing an issue where my code is logging to the console 3 times upon page load and incrementing its index. I cannot figure out why this is happening despite attempting to make adjustments within a useEffect. My project involves using the typewriter-ef ...

How to access a Selenium element using JavaScriptExecutor

My task involves working with a collection of elements in Selenium, specifically located using the By.CssSelector method: var contentRows = new List<TableRow>(); for (var i = 1; i < PositiveInfinity; i++) { var cssSelectorToFind = $"tbody &g ...

Google Script: How to automatically open a newly created text document after its creation

I decided to try out this script for generating Google text documents from Google Spreadsheet data. However, I noticed that the new text document created from a template is always placed in the default folder. This means that I have to manually locate the ...

What is the best way to configure Jenkins to exclude or include specific component.spec.ts files from being executed during the build

Currently, I am facing an issue while attempting to include my spec.ts files in sonarqube for code coverage analysis. However, my Jenkins build is failing due to specific spec.ts files. Is there a way to exclude these particular spec.ts files and include ...

org.openqa.selenium.NoSuchElementException: The element could not be found on the page when verifying the conditions in the if statement

Currently, I am working on a conditional statement to locate an element within my project. if (!(driver.findElement(MobileBy.xpath(ObjRepoProp.getProperty("searchTextBox_XPATH"))).isDisplayed() || driver.findElement(MobileBy.xpath ...

Utilizing Vuex to Access a Component's Property in Vue

Utilizing Vuex in my app is integral for executing asynchronous tasks, such as logging a user into the application. Upon successful login and execution of axios.then(), I aim to notify the component from which I invoked this.$store.dispatch('login&apo ...

Node.js encounters issues when attempting to rename a folder

I am facing an issue while attempting to rename a folder within a WordPress theme after performing search-replace operations using a node script. The renaming process for the folder seems to be unsuccessful. My objective is to change this public_html/wp- ...

Importing modules dynamically in NextJS allows for the loading of

I have a basic function that is responsible for loading a script: const creditCardScript = ( onReadyCB, onErrorCB, ) => { let script = document.createElement("script"); script.type = "text/javascript"; script.src = process.CREDIT_CARD_SCRIPT; ...

Exploring the Use of async: false in jQuery

Can you tell me if there is a distinction between these two settings: $.ajax({ type: "POST", traditional: true, url: '/adminTask/doAction', async: false, <<<<<<<<<<<<<< HERE data: p ...

How to pass a null parameter with jquery's .ajax method

I am facing the following scenario function AddData(title, id) { $.ajax({ type: "POST", url: "topic.aspx/Add", data: JSON.stringify({ "title": title, "id" ...

Steps for constructing an object containing an array of nested objects

I've been working on this problem for some time now, and it's starting to feel like a messy situation that just won't come together. I'm trying to recreate an object with 5 properties and a nested array of objects, but so far, it's ...

What is the process for managing asynchronous requests in servlets?

I wanted to ask a question, but please forgive me if it's not a good one. As someone new to backend development, I am currently working on creating an instant messaging service using Java servlets with GAE. I have a basic idea of how the message sen ...

Having trouble making "jQuery.inArray" function properly in my code

Recently, I made a small interaction where list items are displayed and rotated when clicked - check it out here: http://jsfiddle.net/S79qp/430/ Lately, due to compatibility issues with IE8, I had to switch from using .indexOf() to jQuery.inArray. However ...

managing jquery delays with deferred objects

Using jQuery deferred objects has always been smooth sailing for me and I have a good grasp on how they operate. Recently, I encountered a new scenario where I need to employ them once again. I have a series of similar functions that I am adding to a def ...

Utilizing the Volley library for parsing JSON Data

Hello, I am in need of assistance from someone experienced with the Volley library in order to retrieve JSON data within the following code. I am encountering an error log displaying: D/Volley: [13] BasicNetwork.logSlowRequests: HTTP response for reque ...

Sending a text parameter to the JavaScript Executor within a Selenium framework

Although this question has been asked before, I have searched for multiple answers and have not found a solution to my specific problem. if (driver instanceof JavascriptExecutor) { System.out.println("In try"); ((JavascriptExecutor)driver) ...

Is there a way for me to monitor xmlHttpRequest() activities in IE8 using Firebug Lite?

When it comes to web development, I usually use Firefox for my projects. To ensure cross-browser compatibility, I periodically test my pages in both Firefox and Internet Explorer. Recently, I encountered a problem where one of my AJAX pages was not workin ...

Tips for assigning unique names to each radio input groupNeed to assign unique names to radio

Currently, I am seeking a dynamic solution to alter the name associated with a set of radio input buttons. The situation involves creating a travel itinerary where users can choose between "domestic" and "international." Based on this selection, the corre ...