简体   繁体   中英

Getting No 'Access-Control-Allow-Origin' header is present on the requested resource. error

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;
}

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM