CORS Origin 失败的 Spring Boot
Posted
技术标签:
【中文标题】CORS Origin 失败的 Spring Boot【英文标题】:CORS Origin FAILED Spring Boot 【发布时间】:2019-06-24 05:08:41 【问题描述】:我需要你,因为@CROSSOrigin 不起作用,我不明白为什么,你有我的代码在这里。事实上,我使用 WebService,但我尝试了所有的“Acess-Control-Allow-Origin”但没有任何效果,请帮助我!!
版本为 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, …
pom.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>
Application.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);
Equipment.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;
EquipmentRepository.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>
EquipmentController.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();
【问题讨论】:
【参考方案1】:Did you read the CORS Support section in Spring Documentation?
您也可以尝试使用Spring Higher-Order Components and @EnableCORS,或者如果您不想使用其他依赖项,请使用来自here的@Bean
【讨论】:
您是否尝试使用第二种解决方案? 是的,我试过 Bean 和其他启用 CORS 的方法,我不明白为什么不起作用【参考方案2】:你需要配置一个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);
【讨论】:
以上是关于CORS Origin 失败的 Spring Boot的主要内容,如果未能解决你的问题,请参考以下文章
Spring boot:无法从另一个 Origin 访问安全资源 - CORS - Spring Security - Spring data rest
spring security CORS 过滤器允许没有“Origin”标头的请求