The AJAX functionality for POST, PUT, and DELETE requests is functioning properly, however, the GET request is experiencing CORS

I've been delving into Java, Spring, PHPmyadmin, and a combination of pure HTML and JS for my first API project. I've managed to successfully implement POST, PUT, and DELETE requests, but I'm encountering an issue with GET requests by ID using AJAX. Chrome keeps showing me a CORS error:

Access to XMLHttpRequest at 'http://localhost:8081/dices/players/id?{%22id%22:%22408%22}' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource".

I find it puzzling that this issue occurs only with GET requests while other actions work flawlessly. The backend part of the API functions smoothly and has been verified with POSTMAN. Below is the CORS Filter in Java (I still have some uncertainties about its functionality):

@Component
public class SimpleCORSFilter implements Filter {
    private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);
    public SimpleCORSFilter() {
        log.info("SimpleCORSFilter init");
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, X-HTTP-Method-Override, X-Requested-With, remember-me");
        chain.doFilter(req, res);
    }
    @Override
    public void init(FilterConfig filterConfig) {
    }
}

Also included below is my function in JS (similar to the working DELETE by id function) that's causing the CORS error:

//GET PLAYER BY ID

function getById() {

    let playerID = document.getElementById("playerID").value;

        let playerToShow = {
            id: playerID,
        }

        let shownPlayer = JSON.stringify(playerToShow);

        $.ajax({
            type: "GET",
            url: "http://localhost:8081/dices/players/id",
            contentType: "application/json",
            data: shownPlayer, 
            success: function (data) {

                document.getElementById("data").innerHTML = JSON.stringify(data);
                console.log(data);
            },
            error: function () {

                alert("Something went wrong!);
            }
        });
    } 
}

The complex nature of CORS is leaving me perplexed, so any insights or suggestions would be greatly appreciated! Thank you in advance, and apologies for any language errors!

Answer №1

After some thought, I believe I have finally figured it out. Instead of passing JSON data, you should be passing query string parameters in the GET request.

let shownPlayer = $.param(playerToShow);

When using stringify function - "{\"id\":\"1234\"}"

When applying param function - "id=1234"

Answer №2

Ensure to include the following code snippet in your doFilter method right before executing the chain.doFilter line

if (request.getMethod().equals("HEAD")) {
    response.setStatus(HttpServletResponse.SC_OK);
    return;
}

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

Fragment ViewPager in Android fails to function properly when nested within another Fragment

To display each fragment, add the fragments and initialize the pager adapter. private void slide() { List<Fragment> fragments = new Vector<Fragment>() ; fragments.add(Fragment.instantiate(getActivity(), imageone.class.getName( ...

XML is struggling to load content when using ajax requests

I am attempting to utilize ajax to load an xml file. I have made adjustments to the sample code provided by W3Schools <html> <head> <script> function showBus(str) { if (str == "") { ...

All file upload requests consistently result in a status code of 400

I am encountering an issue with file uploading in Express. Every time I send a request with multipart/form-data, I receive a 400 bad request response with no error message, just an empty object. Currently, I am using busboy-body-parser for parsing multipar ...

What steps can be taken to stop clients from sending an OPTION request prior to each GET?

Is there a way to deactivate the behavior of the client performing an OPTIONS request before every GET request? ...

Unable to display JSON results in a tabular format

After successfully implementing the AJAX method in jQuery, I am able to receive a response. However, I am encountering difficulties when trying to display the arrays in a table format. success:function(resp){ var json =JSON.parse(JSON.stringif ...

Converting units to rem dynamically in CSS: a comprehensive guide

Hey there, I'm currently trying to dynamically convert units into rem in CSS and facing some issues. I have set the root font-size as 23px The current font-size is 16px The expected result should be 16 / 23 => 0.695rem Question: I am looking for ...

The ajax request does not retrieve links from other ajax requests

My userscript is set up to trigger an ajax call using GM_xmlhttprequest to load a basic page with text and links into a div called "debug". Everything is running smoothly so far. However, I now want every link in the requested document to also trigger a gm ...

Building a JSON tree model in a Spring application using a list

I'm struggling with JSON. I have a user_id from the client-side and need to check the groups associated with this user_id. After retrieving data from the database, I place it into a list. I have included this annotation in my xml file: <mvc:anno ...

Zendesk API integration with Angular is experiencing issues with retrieving data as a result of a CORS restriction

I have been working with the Zendesk API and have encountered a problem. Despite being able to successfully send POST requests (even though the response indicates an error), I am unable to make GET requests using my Angular 4 application along with HttpCli ...

Java, organizing classes into stacks

Is there a streamlined approach to creating a class that can contain other classes and be added to an array? I envision a class with 'name', 'val1', and 'val2' attributes. My initial thought was: public class SubClass { pri ...

Mongoose: An unexpected error has occurred

Recently, I developed an express app with a nested app called users using Typescript. The structure of my app.js file is as follows: ///<reference path='d.ts/DefinitelyTyped/node/node.d.ts' /> ///<reference path='d.ts/DefinitelyTyp ...

What is the significance of declaring a constant array in JavaScript?

Does declaring an array as a constant in JavaScript prevent it from changing size, or does it mean that the values inside the array cannot be modified? handleClick(i) { const squares = this.state.squares.slice(); squares[i] = 'X'; this.setState( ...

efforts to activate a "click" with the enter key are unsuccessful

I'm attempting to enhance user experience on my site by triggering the onclick event of a button when the enter key is pressed. I've tried various methods below, but all seem to have the same issue. Here is my HTML (using Pug): input#userIntere ...

Send array as data in an AJAX request using the $.ajax() method

I attempted the following code snippet but was unable to retrieve an array list. It is returning 'null' var data=[]; data[0] = '1'; data[1] = '2'; $.ajax({ url: '@Url.Action("AddFreque ...

Retrieving the href attribute's value from a loaded link using AJAX in jQuery

I am currently working on updating individual records in my database using AJAX. Everything seems to be functioning correctly, but I have encountered an issue where, after the first update is successfully returned, subsequent updates do not work properly. ...

Combining two sets of elements in Java to form a Json using Jackson

Is there a way to combine two List of objects retrieved from the database into a single object in order to serialize with Jackson and deserialize in the view? ObjectMapper mapper = new ObjectMapper(); jsonTutorias = mapper.writeValueAsString(tuto ...

Customizing React component properties within a Styled Component

I have been experimenting with styled components to customize the appearance of basic material-ui React components. My goal is to pass props into the MUI component and then use styled components to apply CSS styling. One interesting aspect is being able t ...

Matching request parameters with a JSON object using node.js and express framework

After uncommenting the lines, the code runs smoothly. However, whenever I enable the 'else' statement, I consistently receive a 'not found' message even when there is a match between req.params.code and data.airports[i].code. var exp ...

Sorting floating point numbers with AngularJS orderBy

JS: (function(angular) { 'use strict'; angular.module('orderByExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.friends = [{name:'John', phone:'2.5-3. ...

Has the AJAX functionality been removed from the form options in Gravity Forms version 1.8.4?

Just recently updated my WordPress plugins and now have Gravity Forms v1.8.4 installed. However, despite documentation and forum comments suggesting that it is possible to create AJAX-style forms (as long as reCAPTCHA is not used), I cannot find the optio ...