javascript - 无法从列表中获取单个用户数据 - 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>
解决方案
在这种情况下,您需要在 forEach 循环中使用索引:
<% obj.data.forEach(function(o, index) { %>
<button type="button" class="btn btn-info">
<a href="/<%= index %> ">
<%= o["first_name"] %>
</a>
</button>
<% }); %>
推荐阅读
- node.js - requests 模块返回带有无序项目的 JSON
- node.js - 使用节点生成 ClientHello 和 ServerHello
- mongodb - 通过表单从不同字段上传多个文件并使用express multer存储到mongodb数据库中
- javascript - React 本机 webview 自动链接导致“包 com.reactnativecommunity.webview.events 不存在”错误。你知道有什么解决办法吗?
- java - Viewholder 上的空指针
- c# - NJsonSchema 对象验证
- javascript - 当要设置动画的项目位于可滚动视图前面时,Panresponder 或 Animated.View 不起作用
- git - 在 AEM 中创建可编辑模板的正确方法是什么?
- javascript - 将每个奇数单词包装在跨度标记 jquery 中
- javascript - 如何使用背景图像导出画布?