我的项目是创建一个用于在其中输入一些文本的输入页面,并将其发送到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.
)
答案 0 :(得分:3)
如下所示添加CORS配置:
@Configuration
public class CORSConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD");
}
}
答案 1 :(得分:2)
您可以使用“ Access-Control-Allow-Origin”标头在客户端配置cors问题
或尝试使用
@CrossOrigin(origins = "http://localhost:4200")
@GetMapping
public String addGraph(@RequestParam String xml) {
Graph graph = new Graph();
graph.setXml(xml);
graphRepository.save(graph);
String ret = "Graph has been added";
return ret;
}