【问题标题】:My app.get only shows me the first item array我的 app.get 只显示第一个项目数组
【发布时间】:2020-10-08 02:46:01
【问题描述】:

我的 app.get("/clientes") 有问题。它只显示了第一个数组项(Juan Perez,18)。我认为我在句子中做错了什么。我不知道我是否可以在 for 句子中使用 res.send,当我更改 clientes[3].nombre 时,它​​会显示不同的结果。

const app = express();

clientes = [
    {
        nombre: "Juan",
        apellido: "Perez",
        edad: 18
    },
    {
        nombre: "Hernan",
        apellido: "Dominguez",
        edad: 27
    },
    {
        nombre: "Maria",
        apellido: "Torres",
        edad: 42
    },
    {
        nombre: "Daniela",
        apellido: "Garcia",
        edad: 34
    }
];

app.get('/', function(req, res){
    res.send("<h1><center>Esta es la ruta principal</h1></center>");
});

app.get('/clientes', function(req, res){
    for(i=0; i<clientes.length; i++){
        res.send("Nombre: "+clientes[i].nombre+", Apellido: "+clientes[i].apellido+", Edad: "+clientes[i].edad+"<br>");
    }
});

app.get('*', function(req, res){
    res.send("<h1><center>No se pudo encontrar la pagina indicada, vuelva al <a href='/'>menu</a></center></h1>");


});

app.listen(3000, function(){
    console.log("Conectado");
});```

【问题讨论】:

  • 将整个 clientes 作为 JSON 发送

标签: javascript arrays for-loop object


【解决方案1】:

/clientes 端点上,您在for 循环内调用了res.send,因此只发送了第一项。需要先获取整个send 字符串并在res.send 上返回。

app.get('/clientes', function(req, res){
  let clientes = '';
  for(i = 0; i < clientes.length; i ++) {
    clientes += "Nombre: " + clientes[i].nombre + ", Apellido: " + clientes[i].apellido + ", Edad: " + clientes[i].edad + "<br>";
  }

  res.send(clientes);
});

【讨论】:

  • 现在它起作用了,只需将 let clientes 更改为另一个名称。谢谢德里克!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 2016-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-27
相关资源
最近更新 更多