CORS error occurs when making an AJAX request to a SpringBoot controller

I am having trouble passing a JSON object to my controller using AJAX. The issue I am facing is a CORS error that reads as follows:

Access to XMLHttpRequest at ........ from origin 'null' 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.

Below is the Javascript and AJAX call code snippet:

database.on('child_added', function (snapshot) {
        var data = {};
        data["CaptainName"] = snapshot.val().CaptainName;
        data["CookName"] = snapshot.val().CookName;
        data["LogicalConditions"] = snapshot.val().LogicalConditions;

        $.ajax({
          headers:  { 'Access-Control-Allow-Origin': '*' },
          type: "GET",
          contentType: "application/json",
          url:"my-localhost/application/print",
          data: JSON.stringify(data),
          dataType: 'json',
          cache: false,
          success: function(){
            console.log("Successfully sent payload")
          },
          error: function(e){
            console.log("Error:" , e)
          }
        });

Now, here is the controller logic:

@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping("/application")
public class AppController
{
    @PostMapping("/print")
    public void print(@RequestBody String st)
    {
        System.out.println(st);
    }
}

Any suggestions on how to resolve this CORS error?

Answer №1

It may be necessary to configure the following settings in the backend. Insert this code snippet into one of your @Configuration classes, such as SecurityConfiguration.java.

 @Bean
        public FilterRegistrationBean corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(true);
            config.addAllowedOrigin("http://localhost:3000");
            config.addAllowedHeader("*");
            config.addAllowedMethod("*");
            source.registerCorsConfiguration("/**", config);
            FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
            bean.setOrder(0);
            return bean;
        }

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

Seeing the Pending Status in Node.js

I am facing a problem with my Ajax using the POST method. I have set up a server route on node and express.js, but even though my route replies with data, the response is pending and not returning back. Client request setup $('#select-category&apos ...

Error: The method "next" cannot be used with BehaviorSubject

My goal is to share data between sibling components by utilizing a shared service. The first component loads and retrieves a list of Servers from the API, populating a select box with all the servers. I now need to notify the other component when the user ...

Unlocking Fields in SharePoint 2007: A Step-by-Step Guide to Enabling a Disabled Field with Checkbox Activation

Hey there! I'm curious to find out what I might be overlooking... function executeMe(){ if(document.getElementById("ctl00_m_g_ef941f4a_7f2d_4a75_a119_6f009e7a22ad_ctl00_ctl04_ctl04_ctl00_ctl00_ctl04_ctl00_ctl00").checked{ document.getElementById("c ...

Tips for displaying the attributes of a product when making edits within a modal utilizing jquery, ajax, and Laravel

Struggling to update product details through a modal populated with inputs, including dropdowns and radio buttons. Using jQuery AJAX for data retrieval from the table. // show editing modal $('body').on('click','#editrentalhsedeta ...

The merging of $.each operations

Is it possible to combine multiple jQuery functions used to assign and change classes and IDs on elements into a single function rather than having separate functions for each? I am currently using the $.each function in jQuery. var stored = $.each; va ...

What is the best way to save a table to local storage in HTML after dynamically adding rows using JavaScript or AngularJS?

I came across this code on the following link. http://codepen.io/akashmitra/pen/eNRVKo HTML <div ng-app="app" ng-controller="Ctrl"> <table class="table table-bordered table-hover table-condensed"> <tr style="font-weight: bold"> ...

Declaring an array inside a method versus outside and using it as an input can impact the execution time

While utilizing Java to tackle a mathematical problem, I attempted to enhance the efficiency of the solution and noticed a significant increase in execution time without understanding the cause. Despite conducting several tests, I have yet to determine the ...

Unable to conceal iFrame ribbon in Sharepoint Online

Attempting to conceal an Office 365 ribbon in SharePoint, but encountering an issue... TypeError: document.getElementById(...) is null This is the snippet I'm experimenting with; I plan to implement display:none later... document.getElementById(&ap ...

What is the best way to verify that a check should have various attributes using chai-things?

Searching for a way to verify if an array in my mocha tests consists of an Object in my Node.js application, I discovered that with Chai-Things, I can use: [{ pet: 'cat' }, { pet: 'dog' }].should.include({ pet: 'cat' }) or ...

The current export script is experiencing difficulties when working with the next/image component

I am working on a project that I need to build and export, but I am facing an error during the process. Below is the build script found in my package.json file: "scripts": { "build": "next build && next export" } ...

What is the best way to send extra parameters to an ajax callback function?

Currently, I am implementing an ajax call in the following manner: util.AjaxCall(url, successCallbackFunction, errorCallbackFunction); function successCallbackFunction(result) { // Result returned from Ajax } Although everything is functioning correc ...

Detecting when a user navigates backwards on a mobile device using JavaScript

I am currently working on a basic HTML file that includes a JavaScript code snippet: <p>Press The Back Button and see a message!</p> <script> window.onpopstate = function(event) { alert("location: " + document.location); } ...

What's the best way to extract a JSON string from a specific URL?

Looking to store JSON data in an array: arr[ ] array = {"http://www.ip-api.com/json"}; How can I print the JSON data itself instead of just showing "" as a string? ...

Generate image results based on the values selected in a range slider and submit them

After browsing through various sliders on CodePen, I stumbled upon the Range Slider created by cturney that fits my requirements perfectly. However, I have a few tweaks in mind for this range slider. I would like to add a "Submit" button that displays each ...

Determine the number of Fridays that fall between two dates using JavaScript or jQuery

Can you help me calculate the total number of a specific day between two given dates? For instance, if I have a start date and end date stored in a variable, I would like to know how many Fridays fall within that timeframe. ...

Sending color data to fragment shader in JavaScript

I've recently started learning webgl and have a query. I'm attempting to construct a triangle and send the color data to the fragment shader from a js file. Below is my js code: var VSHADER_SOURCE = 'attribute vec4 a_Position;\n&ap ...

The argument type 'bool' in EAzureBlobStorageFile is unrecognized, along with the exception '*** -[__NSArrayM objectAtIndexedSubscript:]'

Encountered some issues... An error occurred with an unknown argument '_Bool' in the method -[EAzureBlobStorageFile configure:key:container:token:]. It seems that RCTConvert needs to be extended to support this type. Also, there was an exceptio ...

Issue with React-Axios: File data being sent to Node server is undefined

My current challenge involves uploading a single file and saving it in a specific folder within my app directory. While I can successfully choose a file on the frontend and update the state of the Uploader component, I encounter an issue when sending a POS ...

Create a number/integer local variable in ibatis声明一种数字/整数类型

DECLARE CommitCmpt int; HERE the variable to use it later BEGIN INSERT INTO test.... Commitcmpt := CommitCmpt + 1 ; END; An error is occurring in this line: CommitCmpt int; com.ibatis.common.jdbc.exception.NestedSQLException: --- Cause: com.mic ...

Tips for canceling an http request in angularjs when the requesting controller has exited its scope

Developed a custom angularjs application with ng-view for loading four different modules using route provider. Each module makes HTTP requests as shown below: var requestManager = { "locations": {}, "employees": {}, "items": {}, "templates ...