Spring Boot REST API客户端调用时POST方法不支持的问题求助
Spring Boot REST API客户端调用时POST方法不支持的问题求助
大家好,我最近碰到了一个很头疼的问题,想请各位大佬帮忙看看:我有一个Spring Boot REST API,用Postman测试的时候一切正常,所有HTTP方法都能按预期工作,但当我从客户端应用(Angular,运行在http://localhost:4200)调用它时,后端和前端都报错了,实在摸不着头脑,麻烦帮我排查下!
后端错误信息
报错内容:
Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' is not supported]
前端错误截图
[![前端错误截图][1]][1]
下面是我相关的代码文件,麻烦大家帮忙看看哪里出了问题:
PersonController.java
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/api/v1/persons") @CrossOrigin(origins = "http://localhost:4200") public class PersonController { @Autowired private PersonRepository personRepository; public PersonController(PersonRepository personRepository) { this.personRepository = personRepository; } @RequestMapping( value = "/api/v1/persons", produces = "application/json", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }, method = RequestMethod.GET) public ResponseEntity<Person> createPerson( @RequestParam String firstname, @RequestParam String lastname, @RequestParam String email, @RequestParam int age, @RequestPart(value = "photo", required = false) MultipartFile photo, @RequestPart(value = "cv", required = false) MultipartFile cv){ try { Person person = new Person(); person.setFirstname(firstname); person.setLastname(lastname); person.setEmail(email); person.setAge(age); if (photo != null && !photo.isEmpty()) { person.setPhoto(photo.getBytes()); } if (cv != null && !cv.isEmpty()) { person.setCv(cv.getBytes()); } System.out.println("Save and upload of the files successfully done"); return ResponseEntity.ok(personRepository.save(person)); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } // Get All Persons @GetMapping public List<Person> getAllPersons() { return personRepository.findAll(); } // Get Person by ID @GetMapping("/{id}") public ResponseEntity<Person> getPersonById(@PathVariable Long id) { Optional<Person> person = personRepository.findById(id); return person.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); } // Update Person @PutMapping("/{id}") public ResponseEntity<Person> updatePerson( @PathVariable Long id, @RequestParam String firstname, @RequestParam String lastname, @RequestParam String email, @RequestParam int age, @RequestParam(value = "photo", required = false) MultipartFile photo, @RequestParam(value = "cv", required = false) MultipartFile cv) { Optional<Person> existingPerson = personRepository.findById(id); if (existingPerson.isPresent()) { Person person = existingPerson.get(); person.setFirstname(firstname); person.setLastname(lastname); person.setEmail(email); person.setAge(age); try { if (photo != null && !photo.isEmpty()) { person.setPhoto(photo.getBytes()); } if (cv != null && !cv.isEmpty()) { person.setCv(cv.getBytes()); } } catch (IOException e) { System.out.println("There is something going wrong: " + e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } return ResponseEntity.ok(personRepository.save(person)); } else { return ResponseEntity.notFound().build(); } } // Download Person's Photo @GetMapping("/{id}/photo") public ResponseEntity<byte[]> getPersonPhoto(@PathVariable Long id) { Optional<Person> person = personRepository.findById(id); if (person.isPresent() && person.get().getPhoto() != null) { return ResponseEntity.ok() .header(HttpHeaders.CONTENT_TYPE, "image/png") .body(person.get().getPhoto()); } return ResponseEntity.notFound().build(); } // Download Person's CV @GetMapping("/{id}/cv") public ResponseEntity<byte[]> getPersonCv(@PathVariable Long id) { Optional<Person> person = personRepository.findById(id); if (person.isPresent() && person.get().getCv() != null) { return ResponseEntity.ok() .header(HttpHeaders.CONTENT_TYPE, "application/pdf") .body(person.get().getCv()); } return ResponseEntity.notFound().build(); } // Delete Person @DeleteMapping("/{id}") public ResponseEntity<Void> deletePerson(@PathVariable Long id) { if (personRepository.existsById(id)) { personRepository.deleteById(id); return ResponseEntity.noContent().build(); } else { return ResponseEntity.notFound().build(); } } }
SecurityConfig.java
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import java.util.List; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()) // Disable CSRF .cors(cors -> cors.configurationSource(corsConfigurationSource())) // Enable CORS .authorizeHttpRequests(auth -> auth .requestMatchers(HttpMethod.POST,"/api/v1/persons/**").permitAll() // Allow all requests to this path .anyRequest().permitAll() // Allow all requests globally (disable authentication) ); return http.build(); } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(List.of("http://localhost:4200")); configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); configuration.setAllowedHeaders(List.of("*")); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }
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 https://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>3.4.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>nl.alexandarabski</groupId> <artifactId>person-details</artifactId> <version>0.0.1-SNAPSHOT</version> <name>person-details</name> <description>Person details project for Spring Boot</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>17</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
备注:内容来源于stack exchange,提问作者TheRealKing
相关产品推荐
相关产品推荐

