[英]How to redirect user to home page with his ID after authentication using Node.js and Passport?
[英]How to get an entire User by searching for his ID - NODE.JS
我正在使用這樣的 json 文件:{ id: 1, username: janedoe, firstName: jane, ... } { id: 2, username: welele, firstName; 韋萊萊,... }
我想要一個 GET 方法,執行這條路線 "/user/janedoe" (/user/username) 返回給我這個 json: { id: 1, username: janedoe, firstName: jane, ... }
假設您提供了所有必需的信息,這里是它如何工作的示例。
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);
}
}
});
您可以選擇任何其他選項來讀取文件。 要通過用戶名查找特定用戶,您需要從請求參數中獲取用戶名。 比這里我們的原生 js function 如何從數組中獲取它 默認情況下,如果找不到項目,則返回未定義(您可以在此處閱讀更多信息)因此您返回 404 未找到消息或 200 用戶 object。
首先解析 JSON 然后使用JS數組內置方法查找結果。
const data = JSON.parse(yourjsondata);
const result = data.find(user => user.username == 'janedoe');
假設您的用戶在一個名為:data 的數組中。
您可以使用 find 方法:
您必須執行以下操作:
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.