获得No' Access-Control-Allow-Origin'标头出现在请求的资源上。错误

时间:2018-05-22 21:53:42

标签: java spring angular

我在后端使用Angular,在后端使用Java Spring但是我收到错误:No 'Access-Control-Allow-Origin' header is present on the requested resource.,而我确信CORS已启用。这是我的配置文件:

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("/**");
    }
}

它的工作原理我可以毫无问题地完成其他所有请求,但我服务中的这个PUT请求给了我错误:

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

这是我的服务器端:

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

1 个答案:

答案 0 :(得分:1)

无需添加此配置

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

只需在类级别或方法级别的Controller类中添加如下所示

@CrossOrigin(origins = "http://localhost:4200")