CORS 预检选项请求出现 403 错误。怎么修?

Aym*_*ric 2 java cors spring-boot angular

我的项目是创建一个输入页面,用于在其中输入一些文本并将其发送到 mysql (phpmyadmin) 。我正在使用 spring-boot 2.1.4 和 Angular 7。提前感谢您的调查!爱

我专注于 GraphController.java 并尝试使用@CrossOrigin. 我试图在全局中调用它,但什么也没有......这是我的来源https://spring.io/blog/2015/06/08/cors-support-in-spring-framework 我也什么也没尝试

我的实体(Graph.java)

@Entity(name = "graphiques")
@Table(name ="graphiques")
@Data
@NoArgsConstructor
@AllArgsConstructor

public class Graph {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name ="id")
  private Long id;
  @Column(name ="xml")
  private String xml;

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getXml() {
    return xml;
  }

  public void setXml(String xml) {
    this.xml = xml;
  }

}
Run Code Online (Sandbox Code Playgroud)

我的 GraphController.java

@RestController
@CrossOrigin
@RequestMapping("/insert")
public class GraphController {
  @Autowired
  GraphRepository graphRepository;

  @GetMapping
  @ResponseBody
  public String addGraph(@RequestParam String xml) {
    Graph graph = new Graph();
    graph.setXml(xml);
    graphRepository.save(graph);
    String ret = "Graph has been added";
    return ret;
  }
Run Code Online (Sandbox Code Playgroud)

我在 Angular 中的 xml-insert-form.component.ts

  insertForm: FormGroup;
  xml: string;
  submitted = false;
  graph: Graph;

  initForm() {
    this.insertForm = this.formBuilder.group({
      xml: ['', Validators.required]
    });
  }
  onSubmit() {
    const xml = this.insertForm.get('xml').value;
    const newGraph = new Graph(xml);
    this.graphService.createNewGraph(newGraph).subscribe(
      graph => {
        console.log('onSubmit OK');
      },
      error => console.log('Erreur lors de l\'ajout du nouveau graph')
    );
    this.submitted = true;
  }
Run Code Online (Sandbox Code Playgroud)

在 mysql 中,我有 1 个名为“sogetiauditback”的数据库和一个名为“graphiques”的表,其中包含“id”和“xml”列。(xml 将是输入文本的纯文本)

预期结果:没有 403 错误,输入中的我的数据发送到 mysql 错误消息(谷歌浏览器:
- polyfills.js:3251 OPTIONS http://localhost:8282/insert 403 - Access to XMLHttpRequest at 'http://localhost:8282/insert' from origin 'http://localhost:4200' 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.

DEB*_*NDA 5

添加 CORS 配置如下:

CORSConfig.java

@Configuration
public class CORSConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD");
    }
}
Run Code Online (Sandbox Code Playgroud)