简体   繁体   中英

Unable to get single user data from list - REST API

routes

user.js

view

layout.ejs

user.ejs

users.ejs

app.js

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

I have two GET request. Users.ejs renders three dynamic buttons with an href, also dynamic. User.ejs renders a single user.

I'm passing user id to users.ejs so that when the user clicks on that button, it will render user.ejs and the link will be for eg- 127.0.0.1:8080/1, 127.0.0.1:8080/2, 127.0.0.1:8080/3.

But whenever I click any of the button, the url becomes " http://127.0.0.1:8080/%20+ ".

user.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;

users.ejs

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

user.ejs

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

In this case you need to use index inside forEach loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM