Java 全栈Spring Boot学术项目前端出现奇怪错误

Java 全栈Spring Boot学术项目前端出现奇怪错误,java,mysql,spring-boot,jpa,web-frontend,Java,Mysql,Spring Boot,Jpa,Web Frontend,为了一个学术项目,我们被要求使用Java、Maven和Spring Boot开发一个全栈web系统,试图遵循干净的体系结构和坚实的原则。老师告诉我,最重要的目标是让后端和前端进行交流。我开发的系统很瘦,由几个后端Java类和MySQL db组成,还有一个简化的前端,有2个HTML文件和简洁的CSS和JavaScript代码。 前端页面包括两个JS异步函数;第一个通过其id属性检索配方名称,另一个尝试通过以下JPA@Query注释检索存储在其各自MySQL db表中的配方的完整列表: @Query

为了一个学术项目,我们被要求使用Java、Maven和Spring Boot开发一个全栈web系统,试图遵循干净的体系结构和坚实的原则。老师告诉我,最重要的目标是让后端和前端进行交流。我开发的系统很瘦,由几个后端Java类和MySQL db组成,还有一个简化的前端,有2个HTML文件和简洁的CSS和JavaScript代码。
前端页面包括两个JS异步函数;第一个通过其id属性检索配方名称,另一个尝试通过以下JPA@Query注释检索存储在其各自MySQL db表中的配方的完整列表:

@Query (value = "SELECT matricula, registro, nome FROM RECEITA", nativeQuery = true)
预期返回值为:

但实际显示的结果是:

我会把我在编程方面的专业知识作为初学者来考虑;我不知道错误在哪里,涉及的方法和文件太多了。我将粘贴代码,以便可能有人指出可能的错误。
项目文件夹结构:


App.java:

package com.pucrs.grupo2.Recipes;

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;

@SpringBootApplication
@ComponentScan(basePackages = "com.pucrs.grupo2")
@EnableJpaRepositories(basePackages = {"com.pucrs.grupo2"}) // onde procurar as interfaces dos repositórios do JPA
@EntityScan(basePackages = {"com.pucrs.grupo2"}) // onde procurar as entidades
public class App {
    public static void main(String[] args) {
        
        SpringApplication.run(App.class, args);
        
    }
    
}
ClienteFachadaRemota.java:

package com.pucrs.grupo2.Recipes.interfaces;

import java.util.List;
import com.pucrs.grupo2.Recipes.services.ServicoReceitas;
import com.pucrs.grupo2.Recipes.models.Receita;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/consulta_receita")

public class ClienteFachadaRemota {
    private ServicoReceitas sConsultaRec;

    @Autowired    
    public ClienteFachadaRemota (ServicoReceitas sConsultaRec) {
        this.sConsultaRec = sConsultaRec;
    }

    @CrossOrigin(origins = "*")
    @GetMapping("/dadosreceita")
        public Receita getDadosReceita(@RequestParam Long matricula) {
        Receita receita = sConsultaRec.getNomeReceita(matricula);
        return receita;
    }    
    
    @CrossOrigin(origins = "*")
    @GetMapping("/listareceitas")
    public List<Receita> getTabelaReceitas() {
        List<Receita> receitas = sConsultaRec.findTables();
        return receitas;
    }
    
}
RepositorioReceitas.java:

package com.pucrs.grupo2.Recipes.repositories;

import java.util.List;
import com.pucrs.grupo2.Recipes.models.Receita;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.jpa.repository.Query;

public interface RepositorioReceitas extends CrudRepository<Receita, Long> {
    List<Receita> findByMatricula(long matricula);
    List<Receita> findAll();

    @Query (value = "SELECT matricula, registro, nome FROM RECEITA", nativeQuery = true)
    List<Receita> findTables();

}
package com.pucrs.grupo2.Recipes.services;

import com.pucrs.grupo2.Recipes.models.Receita;
import com.pucrs.grupo2.Recipes.repositories.RepositorioReceitas;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class ServicoReceitas {
    private RepositorioReceitas repReceitas;
    private Receita cacheReceita;

    @Autowired
    public ServicoReceitas(RepositorioReceitas repReceitas) {
        this.repReceitas = repReceitas;
        cacheReceita = null;
    }

    public Receita getNomeReceita(long matricula) {
        List<Receita> receitas = repReceitas.findByMatricula(matricula);
        if (receitas.size() == 0){
            throw new IllegalArgumentException("Receita nao encontrada");
        } else {
            cacheReceita = receitas.get(0) ;
            return cacheReceita;
        }
    }

    public List<Receita> listaDeReceitas() {
        List<Receita> receitas = repReceitas.findAll();
        return receitas;
    }

    public List<Receita> findTables() {
        List<Receita> receitas = repReceitas.findTables();
        return receitas;
    }

}
script.js:

//Consulta nome da receita pelo id
async function consultaNomeReceita(matricula) {
    //console.log(matricula);

    let url = "http://localhost:8080/consulta_receita/dadosreceita";
    url = url + "?matricula="+matricula;

    try {
        let resposta = await fetch(url);
        //console.log(resposta);
        if (resposta.ok){
            let dados = await resposta.json();
            //console.log(dados);
            return dados;
        }else{
            //console.log(resposta.status+", text="+resposta.statusText);
            return null;
        }
    }catch(erro){
        console.log(erro);
    }

}

//Mostra Lista Receitas
async function listaReceitas() {
    //console.log(matricula);

    let url = "http://localhost:8080/consulta_receita/listareceitas";
    //url = url + "?matricula="+matricula;

    try {
        let resposta = await fetch(url);
        //console.log(resposta);
        if (resposta.ok) {
            let dados = await resposta.json();
            //console.log(dados);
            return dados;
        } else {
            //console.log(resposta.status+", text="+resposta.statusText);
            return null;
        }
    } catch(erro) {
        console.log(erro);
    }
}

// --- início do programa
document.getElementById("btDados").onclick = async function () {
    let matricula = document.getElementById("matricula").value;
    let resposta = await consultaNomeReceita(matricula);
    if (resposta != null){
        let nome = document.getElementById("nomeReceita");
        nome.innerHTML = resposta.nome;
        erro = document.getElementById("erro");
        erro.innerHTML = "";
        //let json = document.getElementById("jsonValor");
        //json.innerHTML = JSON.stringify(resposta);
    } else {
        let nome = document.getElementById("nomeReceita");
        nome.innerHTML = " - ";
        erro = document.getElementById("erro");
        erro.innerHTML = "Erro na consulta dos dados";
    }

}

document.getElementById("btLista").onclick = async function () {
        let resposta = await listaReceitas();
        if (resposta != null){
            let tables = document.getElementById("listareceitas");
            tables.innerHTML = resposta;
            erro = document.getElementById("erro");
            erro.innerHTML = "";
            //let json = document.getElementById("jsonValor");
            //json.innerHTML = JSON.stringify(resposta);
        } else {
            let tables = document.getElementById("listareceitas");
            tables.innerHTML = " - ";
            erro = document.getElementById("erro");
            erro.innerHTML = "Erro na consulta dos dados";
        }
    
    }
有什么想法吗?

Project的GitHub Repo URL:

在试图显示整个JSON检索对象的最后一段代码的script.js文件中,您应该循环整个结果respota,并将其显示到前端:如下所示:

const response=等待获取('http://localhost:3000/users/'); const data=wait response.json()


您可能会发现这个url也很有用:

正如@Bleard Rexhaj所提到的,您的数据包含一个数组,您可以将代码更改为以下内容。此外,我会考虑使用一个JavaScript框架的UI,它将大大提高您的代码质量。一些流行的我认为是RACT.JS或VU.JS.

document.getElementById("btLista").onclick = async function () {
    let resposta = await listaReceitas();
    if (resposta != null){
        let tables = document.getElementById("listareceitas");
        let innerHTML = '';
        resposta.forEach(obj => {
            innerHTML += ' - ' + obj.nome;
        });
        tables.innerHTML = innerHTML;
        erro = document.getElementById("erro");
        erro.innerHTML = "";
    } else {
        let tables = document.getElementById("listareceitas");
        tables.innerHTML = " - ";
        erro = document.getElementById("erro");
        erro.innerHTML = "Erro na consulta dos dados";
    }

}
.recipes-icon {
    content:url(file:///D:/Documentos/Docs/PUCRS/FdDdSW/TF/TF-FDS/Recipes/src/main/resources/static/r_spatula.jpg);
    width: 800px;
    height: 600px;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

 div {
    position: fixed;
    color: brown;
    font-family: sans-serif;
    font-size: 300%;
    left: 50%;
    bottom: 100px;
    transform:translate(-50%, -50%);
    margin: 0 auto;
    cursor: pointer;
}

 h1 {
    color: brown;
    width: 100%;
    text-align: center;
  }
  
.ul {
    list-style: none;
    padding: 0;
    margin: 0;
  }
  
.label {
    display: inline-block;
    width: 90px;
    text-align: right;
  }
  
.input {
    font: 1em sans-serif;
    width: 300px;
    box-sizing: border-box;
    border: 1px solid #999;
  }
  
.input:focus {
    border-color: #000;
  }
  
.button {
    margin:auto;
    text-align: center;
  }
  
#erro {
  color:red;
  }
//Consulta nome da receita pelo id
async function consultaNomeReceita(matricula) {
    //console.log(matricula);

    let url = "http://localhost:8080/consulta_receita/dadosreceita";
    url = url + "?matricula="+matricula;

    try {
        let resposta = await fetch(url);
        //console.log(resposta);
        if (resposta.ok){
            let dados = await resposta.json();
            //console.log(dados);
            return dados;
        }else{
            //console.log(resposta.status+", text="+resposta.statusText);
            return null;
        }
    }catch(erro){
        console.log(erro);
    }

}

//Mostra Lista Receitas
async function listaReceitas() {
    //console.log(matricula);

    let url = "http://localhost:8080/consulta_receita/listareceitas";
    //url = url + "?matricula="+matricula;

    try {
        let resposta = await fetch(url);
        //console.log(resposta);
        if (resposta.ok) {
            let dados = await resposta.json();
            //console.log(dados);
            return dados;
        } else {
            //console.log(resposta.status+", text="+resposta.statusText);
            return null;
        }
    } catch(erro) {
        console.log(erro);
    }
}

// --- início do programa
document.getElementById("btDados").onclick = async function () {
    let matricula = document.getElementById("matricula").value;
    let resposta = await consultaNomeReceita(matricula);
    if (resposta != null){
        let nome = document.getElementById("nomeReceita");
        nome.innerHTML = resposta.nome;
        erro = document.getElementById("erro");
        erro.innerHTML = "";
        //let json = document.getElementById("jsonValor");
        //json.innerHTML = JSON.stringify(resposta);
    } else {
        let nome = document.getElementById("nomeReceita");
        nome.innerHTML = " - ";
        erro = document.getElementById("erro");
        erro.innerHTML = "Erro na consulta dos dados";
    }

}

document.getElementById("btLista").onclick = async function () {
        let resposta = await listaReceitas();
        if (resposta != null){
            let tables = document.getElementById("listareceitas");
            tables.innerHTML = resposta;
            erro = document.getElementById("erro");
            erro.innerHTML = "";
            //let json = document.getElementById("jsonValor");
            //json.innerHTML = JSON.stringify(resposta);
        } else {
            let tables = document.getElementById("listareceitas");
            tables.innerHTML = " - ";
            erro = document.getElementById("erro");
            erro.innerHTML = "Erro na consulta dos dados";
        }
    
    }
data.forEach(obj => {
    Object.entries(obj).forEach(([key, value]) => {
        console.log(`${key} ${value}`);
    });
    console.log('-------------------');
});
document.getElementById("btLista").onclick = async function () {
    let resposta = await listaReceitas();
    if (resposta != null){
        let tables = document.getElementById("listareceitas");
        let innerHTML = '';
        resposta.forEach(obj => {
            innerHTML += ' - ' + obj.nome;
        });
        tables.innerHTML = innerHTML;
        erro = document.getElementById("erro");
        erro.innerHTML = "";
    } else {
        let tables = document.getElementById("listareceitas");
        tables.innerHTML = " - ";
        erro = document.getElementById("erro");
        erro.innerHTML = "Erro na consulta dos dados";
    }

}