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

2023-12-06

我的项目是创建一个输入页面,用于在其中输入一些文本并将其发送到 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;
  }

}

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

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

在 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.)


添加 CORS 配置如下:

CORSConfig.java

@Configuration
public class CORSConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD");
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

CORS 预检选项请求出现 403 错误。怎么修? 的相关文章

随机推荐