CORS policy is causing the POST request to be blocked, but the GET and DELETE requests

I've encountered a strange issue with my application. The architecture of my app is as follows: ts (Angular) -> Java (Spring). I was making some GET requests from Angular to Java, as well as DELETE requests without any problems. However, when I tried to add a POST request, things got complicated. My app uses HTTP basic authentication. Here is some code from my data service:

getCurrentCars(id:number){
    const headers = new HttpHeaders({ 'Content-Type':'application/json',
      'Authorization': 'Basic ' + btoa(sessionStorage.getItem('username') + ':' + sessionStorage.getItem('password')) });
    return this.http.get("http://localhost:8080/api/cars/getcurrentcars/"+id.toString(),{headers});
  }
  postNewRepair(name:string, description:string, date:string, idCar:number){
    const headers = new HttpHeaders({ 'Content-Type':'application/json',
      'Authorization': 'Basic ' + btoa(sessionStorage.getItem('username') + ':' + sessionStorage.getItem('password')) });
    let newrepair:Repair= {name: name, date:date, description:description, idCar:idCar}
    this.http.post("localhost:8080/api/repairs/postRepair",newrepair,{headers}).subscribe(resp => console.log(resp));
  }

The GET request works fine, but the POST request doesn't work. Interestingly, the POST request works perfectly fine in Postman.

I have also tried to disable CORS policies, here are some examples:

@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping("/api/repairs")
public class ControllerRepair {
@RequestMapping(method = RequestMethod.POST, value = "/postRepair")

    public void postRepair(@RequestParam String name, @RequestParam String date, @RequestParam String description, @RequestParam Long idCar){
        LocalDate date1 = LocalDate.parse(date);
        System.out.println("aaa");
        iRepairService.postRepair(name, date1, description, idCar);
    }
}

Here is a snippet from the HTTP configuration:

http
                .cors().and()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/api/repairshops/**").hasAuthority("REPAIR_SHOP")
                .antMatchers("/api/clients/**").hasAnyAuthority("CLIENT","REPAIR_SHOP")
                .antMatchers("/login/**").fullyAuthenticated()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();

I even attempted using a CORS configuration class I found on StackOverflow, but it not only failed to solve the issue with the POST request but also disrupted my other GET and DELETE requests.

Access to XMLHttpRequest at 'localhost:8080/api/repairs/postRepair' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross-origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

Could it be that I'm missing some headers in my HTTP POST request to make it work?

Answer №1

It appears that the 'http' is missing in the URL of the post request. We should include it just like in the previous GET request and attempt again.

this.http.post("http://localhost:8080/api/repairs/postRepair", newrepair, { headers })
    .subscribe(resp => console.log(resp));

Answer №2

By utilizing your current settings (http.cors()), you are essentially employing the default cors configuration that is offered by spring (https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/cors.html). To tailor it to fit your specific needs, you can refer to the instructions outlined in this guide ().

If you wish to experiment with it, you can consider using the following code snippet as a temporary fix:

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**").allowedMethods("*");
}

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

Cache for JSON Schema in VS Code

After updating to TypeScript 1.5 (now out of beta), I am eager to utilize the json schema helpers in VS Code. Upon configuring tsconfig.json, I noticed that only commonjs and amd module options are available, while umd and system are missing based on this ...

What is the best way to create an optional object parameter in Typescript?

I'm working on a function that looks like this: const func = (arg1: string, { objArg = true }:{ objArg: string }) => { // some code } Is it possible to make the second parameter (an object) optional? ...

"Enhancing Angular's `mat-table` with bi-directional data binding

I'm running into an issue with the binding of mat-checkbox within a mat-table. The table's dataSource is a simple array of objects, each containing a boolean property for selection. However, I can't seem to get the two-way binding working pr ...

Utilizing Typescript's baseUrl compiler configuration for node development

Is there a way for node's module loader to support TS's baseUrl compiler option? With the introduction of the baseUrl compiler option in TS 2, project relative require() and import requests are now possible. However, this feature requires that ...

WebElement can be seen at times and at other times cannot be seen

Occasionally, the element may appear and disappear intermittently. Furthermore, the element is not currently in the Document Object Model (DOM). What would be the best approach to manage this scenario with Selenium Webdriver? ...

What is the TypeScript type for a delayed async function call using setTimeout()?

So, I have two functions related to fetching credentials from an external API. The first function simply fetches the credentials: const fetchCredentials= async () => { return await fetch(/* url and params */); }; The second function is a bit mo ...

Utilizing Spark and Java to Create a Mapping from String to Tuple2<String, Long>

Currently, I am in the process of learning how to utilize Spark with Java programming language (please refrain from sharing Scala code). My main goal is to execute a basic Spark example, known as the hello world, which involves counting words. To achieve ...

Combining Selenium TestNG (Java) with TestRail test cases: A step-by-step guide

I'm working on a TestRail project with test cases that I've automated using Selenium TestNG. I've been searching for a detailed guide on how to seamlessly integrate my TestRail project's test cases with my Selenium TestNG project. Speci ...

When the parameter is incorrect, the click function still triggers an event

I have a button that triggers a function called check (resp is a reference in my HTML template) <button (click)="check(resp)"> clickMe </button> In my typescript code, I have: check() { console.log("check is clicked") } I ...

Is it possible to customize webpack 4 modules in order to enable Jasmine to spy on their properties?

I've been facing issues trying to run my Jasmine test suite with webpack 4. Ever since I upgraded webpack, I keep getting this error message in almost every test: Error: <spyOn> : getField is not declared writable or has no setter The problem ...

Converting Time Zone to Coordinated Universal Time (UTC) using the Joda-Time library

Here is a code snippet: String twelveHourTime="06:00 PM"; public static DateTime convert12HourTimeTo24HourTime(String twelveHourTime) { DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(AppConstants.TWELVE_HOUR_TIME_ ...

Utilizing 'nestjs/jwt' for generating tokens with a unique secret tailored to each individual user

I'm currently in the process of generating a user token based on the user's secret during login. However, instead of utilizing a secret from the environment variables, my goal is to use a secret that is associated with a user object stored within ...

Is there a Typescript function error that occurs when attempting to rename a key, stating it "could potentially be instantiated with a different subtype"?

I am currently working on a Mongoify type that accepts a type T, removes the id key, and replaces it with an _id key. type Mongoify<T extends {id: string}> = Omit<T, "id"> & { _id: ObjectId }; function fromMongo<T extends ...

Clicking the button fails to trigger the modal popup

Upon clicking a button, I am attempting to open a modal popup but encountering an error: The button click works, however, the popup does not appear after the event. test.only('Create Template', async({ page })=>{ await page.goto('h ...

Endlessly streaming data is requested through HTTP GET requests

I am facing an issue with my code where it requests data endlessly. The service I have retrieves data in the form of an Array of Objects. My intention is to handle all the HTTP requests, mapping, and subscriptions within the service itself. This is because ...

Angular 4 - Automatically scroll to specific list item based on search query input

While I can achieve this with custom JavaScript, I'm curious if Angular 4 has any built-in features that could help. I have a list of checkboxes that are scrollable and a search input above them. My goal is to enable users to quickly jump to a section ...

Executing NestJS code after applying a pipe but before reaching the method handler

Is it possible to insert additional code after all the pipes have transformed but before the method handler is called? https://i.sstatic.net/IjQvv.png ...

Transform variable names from Java and AngularJS conventions to standard English

In my quest, I have successfully used JAVA Reflections to extract attribute names from a class. However, I desire to change the variable naming convention, such as transforming firstName into First Name. I currently contemplate utilizing the .split() meth ...

Uploading files along with additional data fields

I am facing a dilemma with my HTML form that has enctype="multipart/form-data" attribute. I have a DTO class with all the necessary setters and getters. Since I am submitting the form as multipart, I cannot use getParameter() method directly. In my servlet ...

Encountering a JSON type mismatch error

Every time my code is executed, I encounter the following error message. JSON.typeMismatch(JSON.java:111) Is there a way to parse a JSONObject that is surrounded by an array? This is the code snippet in question: public class FeedActivity extends App ...