0

I am using Angular in the frontend and Java Spring in the backend but I am getting the error: No 'Access-Control-Allow-Origin' header is present on the requested resource. while I am sure CORS is enabled. This is my configuration file:

package com.aon04.backend.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class CorsConfiguration implements WebMvcConfigurer
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

And it works I can do every other request without a problem but this PUT request in my service gives me the error:

  updateExamById(id, exam: Examen): Observable<Examen> {
    return this.http.put<Examen>(APIURL + '/update/' + id, {file: exam.file, name: exam.naam});
  }

This is my server side of it:

@PutMapping("/update/{id}")
public Exam UpdateExam(@RequestParam("file") MultipartFile file, @RequestParam("name") String name, @PathVariable("id") int id)
{
    Exam newExam = new Exam();
    newExam.setId(id);
    newExam.setSkelet(file.getOriginalFilename());
    newExam.setNaam(name);
    newExam.setCreatedAt(LocalDateTime.now());
    Exam exam2 = ExamFactory.update(newExam);
    examRepository.save(exam2);
    storageService.store(file);
    return newExam;
}
Sinan Samet
  • 5,034
  • 11
  • 40
  • 80

1 Answers1

1

No need to add this configuration

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

Just add like this in your Controller class at class level or method level what u want

@CrossOrigin(origins = "http://localhost:4200")
Rohit Kavthekar
  • 229
  • 1
  • 10
  • You can also have a problem of header in your service so if the cross origin doesn't work add the header in your service with "const headers1 = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});" and you add it to your put request as a third argument – Loïc Thierry May 23 '18 at 07:45
  • In my case while calling rest api from angular's end for post request it works fine for me without adding headers in post request.i have simply added above @ annotation in my controller class. If you want to do more CORS filtering then u can also add CORSfilter.java(search on google) that filters request . – Rohit Kavthekar May 23 '18 at 11:08