我需要你,因为@CROSSOrigin不起作用,我不明白为什么,你这里有我的代码。事实上,我使用 WebService,但我对"控制允许起源"有问题,我尝试了所有方法,但没有任何效果,请帮助我!
带有2.1.2版本的SPRING BOOT项目,我想为ANGULAR 7构建一个REST API
问题:
zone.js:3243 GET http://localhost:8080/apiEquipment/equipments 404
localhost/:1 Access to XMLHttpRequest at 'http://localhost:8080/apiEquipment/equipments' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
zone.js:3243 XHR failed loading: GET "http://localhost:8080/apiEquipment/equipments".
core.js:15714 ERROR
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:8080/apiEquipment/equipments", ok: false, …}
绒球.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>GoSecuriServices</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>GoSecuriServices</name>
<description>Rest API for GoSecuri Application</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
应用.java
package com.example.GoSecuriServices;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@EnableJpaRepositories("com.example.GoSecuriServices.repository")
@EntityScan("com.example.GoSecuriServices.model")
@ComponentScan
@SpringBootApplication
public class GoSecuriServicesApplication {
public static void main(String[] args) {
SpringApplication.run(GoSecuriServicesApplication.class, args);
}
}
设备.java(我的桌子)
package model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
@Entity
@Table(name = "Equipment")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, allowGetters = true)
public class Equipment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Equipment_id;
@NotBlank
private String EquipmentName;
@NotBlank
private Integer Nb;
// Getters and Setters
public Long getEquipment_id() {
return this.Equipment_id;
}
public void SetEquipment_id(Long id) {
this.Equipment_id = id;
}
public String getEquipmentName() {
return this.EquipmentName;
}
public void setEquipmentName(String name) {
this.EquipmentName = name;
}
public Integer getNb() {
return this.Nb;
}
public void setNb(Integer nb) {
this.Nb = nb;
}
}
设备存储库.java
package repository;
import model.Equipment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EquipmentRepository extends JpaRepository<Equipment, Long> {
}
设备控制器.java
package controller;
import exception.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import model.Equipment;
import repository.EquipmentRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
@RestController
@CrossOrigin(origins = "*", allowedHeaders = "*", maxAge = 3600)
@RequestMapping("/apiEquipment")
public class EquipmentController {
@Autowired
EquipmentRepository equipmentRepository;
@RequestMapping(value= "/apiEquipment/**", method=RequestMethod.OPTIONS)
public void corsHeaders(HttpServletResponse response) {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with");
response.addHeader("Access-Control-Max-Age", "3600");
}
// Get all equipments
@GetMapping("/equipments")
public List<Equipment> getAllEquipments() {
return equipmentRepository.findAll();
}
// Create new equipment
@PostMapping("/equipments")
public Equipment createEquipment(@Valid @RequestBody Equipment equipment) {
return equipmentRepository.save(equipment);
}
// Get a single equipment
@GetMapping("/equipments/{id}")
public Equipment getEquipmentById(@PathVariable(value = "id") Long equipmentId) {
return equipmentRepository.findById(equipmentId)
.orElseThrow(() -> new ResourceNotFoundException("Equipment", "id", equipmentId));
}
// Update a Equipment
@PutMapping("/equipments/{id}")
public Equipment updateNote(@PathVariable(value = "id") Long equipmentId,
@Valid @RequestBody Equipment equipmentDetails) {
Equipment equipment = equipmentRepository.findById(equipmentId)
.orElseThrow(() -> new ResourceNotFoundException("Equipment", "id", equipmentId));
equipment.setEquipmentName(equipmentDetails.getEquipmentName());
equipment.setNb(equipmentDetails.getNb());
Equipment updatedEquipment = equipmentRepository.save(equipment);
return updatedEquipment;
}
// Delete a Equipment
@DeleteMapping("/equipments/{id}")
public ResponseEntity<?> deleteEquipment(@PathVariable(value = "id") Long equipmentId) {
Equipment equipment = equipmentRepository.findById(equipmentId)
.orElseThrow(() -> new ResourceNotFoundException("Equipment", "id", equipmentId));
equipmentRepository.delete(equipment);
return ResponseEntity.ok().build();
}
}
您是否阅读了 Spring 文档中的 CORS 支持部分?
您也可以尝试使用Spring 高阶组件和@EnableCORS,或者如果您不想使用其他依赖项,请使用此处@Bean
您需要按如下方式配置 Web 跨域配置:
package com.liukai.routermanagement.config;
import com.liukai.routermanagement.interceptor.LoginHandlerInterceptor;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@SpringBootConfiguration
public class MyWebMvcConfig extends WebMvcConfigurationSupport {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login","/router/login","/user/registered");
super.addInterceptors(registry);
}
// this main mothod,Just add this method
@Override
protected void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods("GET","POST","PUT","DELETE");
super.addCorsMappings(registry);
}
}