You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular+SpringBoot+PostgreSQL项目Http 500错误排查求助

Angular+SpringBoot项目500错误排查与修复

搭建了基于Angular+SpringBoot(PostgreSQL数据库)的项目,已配置CORS,确认数据库连接正常,参数、接口路径及函数逻辑看似无误,但调用http://localhost:8080/api/utenti时返回HttpErrorResponse 500错误,修改前后端路径后问题仍未解决。以下是相关代码、错误信息及解决方案:


CORS配置

package esercizio3.esercizio3.Configurations;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/utenti")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET")
                .allowedHeaders("*") // Allow all headers
                .allowCredentials(false);
    }
}

Controller代码

package esercizio3.esercizio3.Controllers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import esercizio3.esercizio3.model.utente;
import esercizio3.esercizio3.utenteREPO.utenteREPO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;


@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/api")
public class utentecontroller {

  @Autowired
  utenteREPO utenterep;


  @GetMapping("/utenti")
  public  ResponseEntity<List<utente>> getAllutenti(@RequestParam (required = false)String email) {
    try {
      List<utente>utenti=new ArrayList<utente>();

      if(email==null)
        utenterep.findAll().forEach(utenti::add);
        else{
          utenterep.findByEmail(email).forEach(utenti::add);
          if (utenti.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT );
          }
        }
         return new ResponseEntity<>(utenti, HttpStatus.OK);
    } catch (Exception e) {
      return new ResponseEntity<>(null,HttpStatus.INTERNAL_SERVER_ERROR);
    }

  }

  @PostMapping("/utenti")
  public ResponseEntity<utente> createutente(@RequestBody utente utente) {
      try {
          utente _utente = utenterep.save(new utente(
                  utente.getEmail(),
                  utente.getNome(),
                  utente.getcognome(),
                  utente.getCittadiresidenza(),
                  utente.getCodicefiscale(),
                  utente.getVia(),
                  utente.getProvinciadiresidenza()
          ));
          return new ResponseEntity<>(_utente, HttpStatus.CREATED);
      } catch (Exception e) {
          
          return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
      }
  }

  /*@PostMapping("/utenti")
public ResponseEntity<utente> createutente(@RequestBody utente utente) {
    try {
        utente _utente = utenterep.save(new utente(
                utente.getEmail(),
                utente.getNome(),
                utente.getCognome(),
                utente.getCittadiresidenza(),
                utente.getCodicefiscale(),
                utente.getVia(),
                utente.getProvinciadiresidenza()
        ));
        return new ResponseEntity<>(_utente, HttpStatus.CREATED);
    } catch (Exception e) {
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
 */

}

Model代码

package esercizio3.esercizio3.model;

import java.io.Serializable;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class utente implements Serializable{
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(nullable = false,updatable = false)

  private String email;

    @Column(name = "nome")
    private String nome;

    @Column(name = "cognome")
    private String cognome;

    @Column(name = "codicefiscale")
    private String codicefiscale;

    @Column(name = "provinciadiresidenza")
    private String provinciadiresidenza;

    @Column(name = "cittadiresidenza")
    private String cittadiresidenza;

    @Column(name = "via")
    private String via;

  public utente() {
  }

  public utente(String email, String nome, String cognome, String codicefiscale, String provinciadiresidenza, String cittadiresidenza, String via) {
    this.email = email;
    this.nome = nome;
    this.cognome = cognome;
    this.codicefiscale = codicefiscale;
    this.provinciadiresidenza = provinciadiresidenza;
    this.cittadiresidenza = cittadiresidenza;
    this.via = via;
  }

  public String getEmail() {
    return this.email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  public String getNome() {
    return this.nome;
  }

  public void setNome(String nome) {
    this.nome = nome;
  }

  public String getcognome() {
    return this.cognome;
  }

  public void setcognome(String cognome) {
    this.cognome = cognome;
  }

  public String getCodicefiscale() {
    return this.codicefiscale;
  }

  public void setCodicefiscale(String codicefiscale) {
    this.codicefiscale = codicefiscale;
  }

  public String getProvinciadiresidenza() {
    return this.provinciadiresidenza;
  }

  public void setProvinciadiresidenza(String provinciadiresidenza) {
    this.provinciadiresidenza = provinciadiresidenza;
  }

  public String getCittadiresidenza() {
    return this.cittadiresidenza;
  }

  public void setCittadiresidenza(String cittadiresidenza) {
    this.cittadiresidenza = cittadiresidenza;
  }

  public String getVia() {
    return this.via;
  }

  public void setVia(String via) {
    this.via = via;
  }

  @Override
  public String toString() {
    return "{" +
      " email='" + getEmail() + "'" +
      ", Nome='" + getNome() + "'" +
      ", cognome='" + getcognome() + "'" +
      ", codicefiscale='" + getCodicefiscale() + "'" +
      ", provinciadiresidenza='" + getProvinciadiresidenza() + "'" +
      ", cittadiresidenza='" + getCittadiresidenza() + "'" +
      ", via='" + getVia() + "'" +
      "}";
  }
}

Repository代码

package esercizio3.esercizio3.utenteREPO;

import org.springframework.data.jpa.repository.JpaRepository;

import esercizio3.esercizio3.model.utente;
import java.util.List;


public interface utenteREPO extends JpaRepository<utente,String> {

  List<utente> findByEmail(String email);
  List<utente> findByNome(String nome);
}

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.2.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>esercizio3</groupId>
    <artifactId>esercizio3</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>esercizio3</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</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-web</artifactId>
        </dependency>
  <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</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>

Angular端错误信息

HttpErrorResponse
error
: 
null
headers
: 
_HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message
: 
"Http failure response for http://localhost:8080/api/utenti: 500 OK"
name
: 
"HttpErrorResponse"
ok
: 
false
status
: 
500
statusText
: 
"OK"
url
: 
"http://localhost:8080/api/utenti"
[[Prototype]]
: 
HttpResponseBase

问题根源与修复方案

1. 核心错误:Model主键配置冲突

utente类中email字段同时标记为@Id和@GeneratedValue(strategy = GenerationType.AUTO),但String类型无法适配PostgreSQL的自增主键生成逻辑,导致数据库操作失败。

  • 修复方式:
    • 若email作为业务主键(无需自增),移除@GeneratedValue注解:
      @Id
      @Column(nullable = false, updatable = false)
      private String email;
      
    • 若需自增主键,新增数值类型主键字段,将email设为唯一约束:
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Long id;
      
      @Column(unique = true, nullable = false)
      private String email;
      
      同时更新Repository泛型为JpaRepository<utente, Long>。

2. 补充异常日志定位问题

在Controller的catch块中添加日志输出,便于直接查看错误详情:

catch (Exception e) {
    e.printStackTrace(); // 或使用SLF4J日志框架打印
    return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}

3. 清理冗余CORS配置

保留一种CORS配置方式即可,比如删除全局CorsConfig类,仅保留Controller上的@CrossOrigin(origins = "http://localhost:4200"),避免冲突。

4. 校验数据库表结构

确保PostgreSQL中utente表的字段类型与Model类匹配,比如email字段为VARCHAR类型且长度足够。


内容的提问来源于stack exchange,提问作者Roberto Longo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 18:27:02