首页 > 解决方案 > 无法从列表中获取单个用户数据 - REST API

问题描述

路线

用户.js

看法

布局.ejs

用户.ejs

用户.ejs

应用程序.js

REST API -“ https://reqres.in/api/users?page=2

我有两个 GET 请求。Users.ejs 使用 href 渲染三个动态按钮,也是动态的。User.ejs 呈现单个用户。

我将用户 ID 传递给 users.ejs,这样当用户单击该按钮时,它将呈现 user.ejs,并且链接将用于例如 - 127.0.0.1:8080/1、127.0.0.1:8080/2、 127.0.0.1:8080/3。

但是每当我单击任何按钮时,网址都会变为“ http://127.0.0.1:8080/%20+ ”。

用户.js

const express = require("express");
const router = express.Router();
const request = require("request");

global.url = "https://reqres.in/api/users?page=2";

router.get("/users", (req, res) => {
request.get(url, function(err, resp, body) {
 const parse = JSON.parse(body);

res.render("users", {
    obj : parse
    });
  });
});

router.get("/:id", (req, res) => {
request.get(url, (err, resp, body) => {
const obj = JSON.parse(body);
global.user = obj.data[req.params.id];

console.log('USER:', user);

res.render('user', { 
    user
    });
  });
});

module.exports = router;

用户.ejs

<% obj.data.forEach(function(o) { %>
<button type="button" class="btn btn-info">
<a href="/ + <%= JSON.stringify(user) %> "> 
    <%= o["first_name"] %> 
</a>
</button>
<% }); %>

用户.ejs

<h1><%= JSON.stringify(user) %></h1>

标签: javascriptnode.jsjsonexpressejs

解决方案


在这种情况下,您需要在 forEach 循环中使用索引:

<% obj.data.forEach(function(o, index) { %>
<button type="button" class="btn btn-info">
<a href="/<%= index %> "> 
    <%= o["first_name"] %> 
</a>
</button>
<% }); %>

推荐阅读