简体   繁体   English

如何通过搜索他的 ID 来获取整个用户 - NODE.JS

[英]How to get an entire User by searching for his ID - NODE.JS

I'm using a json file like this: { id: 1, username: janedoe, firstName: jane, ... } { id: 2, username: welele, firstName;我正在使用这样的 json 文件:{ id: 1, username: janedoe, firstName: jane, ... } { id: 2, username: welele, firstName; Welele, ... }韦莱莱,... }

I want a GET method that doing this route "/user/janedoe" (/user/username) returns to me this json: { id: 1, username: janedoe, firstName: jane, ... }我想要一个 GET 方法,执行这条路线 "/user/janedoe" (/user/username) 返回给我这个 json: { id: 1, username: janedoe, firstName: jane, ... }

Let's say that you provided all required information, here is example how it works.假设您提供了所有必需的信息,这里是它如何工作的示例。

import { readFile } from 'fs/promises';
// Add try/catch if needed
let data = JSON.parse(await readFile("filename.json", "utf8"));

router.get('/users/:username', (req, res) => {
    const userName = req.params.username;
    if (data.length > 0) {
       const user = data.find(u => u.username === userName);
       if (typeof user === 'undefined') {
         res.status(404).send({
             error: "User not found"
         });
       } else {
          res.status(200).send(user);
       }
    }
});

You can choose any other option to read file.您可以选择任何其他选项来读取文件。 To find specific user by username you need to get username from request params.要通过用户名查找特定用户,您需要从请求参数中获取用户名。 Than here us native js function how to get it from array By default if item was not found this return undefined (you can read more here ) So you're returning 404 with not found message or 200 with user object.比这里我们的原生 js function 如何从数组中获取它 默认情况下,如果找不到项目,则返回未定义(您可以在此处阅读更多信息)因此您返回 404 未找到消息或 200 用户 object。

At first parse, the JSON then use the JS array build-in method to find the result.首先解析 JSON 然后使用JS数组内置方法查找结果。

const data = JSON.parse(yourjsondata);
const result = data.find(user => user.username == 'janedoe');

Supposing your user is inside an array named: data.假设您的用户在一个名为:data 的数组中。

You could use find method:您可以使用 find 方法:

You would have to do something like:您必须执行以下操作:

getUser(req, res) {
    const data = // import your file here if necessary
    const username = req.username;
    res.send({user: data.find(user => user.username === username})
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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