英文:
How to create single API for getallUsers and getUser?
问题
To create a single API that can handle both getting all users and a single user, you can use a route like this:
router.get('/:id?', async (req, res) => {
if (req.params.id) {
// Get a single user by ID
const user = await User.findById(req.params.id).select('-password');
if (!user) {
res.status(404).json({ message: 'User not found' });
} else {
res.status(200).json(user);
}
} else {
// Get all users
const userList = await User.find().select('-password');
res.status(200).json(userList);
}
});
This route handles requests with or without an id
parameter. If an id
is provided, it retrieves a single user by ID. If not, it retrieves all users.
英文:
I have to create a single API to get all users and a single user. How can I create an API for this?
Currently, I had APIs like this.
To get All Users:
router.get(`/`, async (req, res) =>{
const userList = await User.find().select('-password')
if(!userList) {
res.status(500).json({success: false})
}
res.send(userList);
})
To get single User:
router.get('/:id' , async (req,res) =>{
const user = await User.findById(req.params.id).select('-password')
if(!user){
res.status(500).json({message: 'The User with give id is not found'})
}
res.status(200).send(user)
})
Now my requirement is that have to create a single API for above both APIs.
How can I solve this?
答案1
得分: 1
你可以告诉客户,如果他们需要所有用户,他们应该将"id"参数设为"all"。
router.get("/:id", async (req, res) => {
if (req.params.id === "all") {
const userList = await User.find().select("-password");
if (!userList) {
res.status(500).json({ success: false });
}
res.send(userList);
} else {
const user = await User.findById(req.params.id).select("-password");
if (!user) {
res.status(500).json({ message: "未找到给定id的用户" });
}
res.status(200).send(user);
}
});
英文:
You can say clients that they should send all as id if they require all the users.
router.get("/:id", async (req, res) => {
if (req.params.id === "all") {
const userList = await User.find().select("-password");
if (!userList) {
res.status(500).json({ success: false });
}
res.send(userList);
} else {
const user = await User.findById(req.params.id).select("-password");
if (!user) {
res.status(500).json({ message: "The User with give id is not found" });
}
res.status(200).send(user);
}
});
答案2
得分: 0
使用路由器
let router = express.Router();
router.get('/:id', function (req, res, next) {
console.log("Specific User Router Working");
res.end();
});
router.get('/all', function (req, res, next) {
console.log("All User Router Working");
res.end();
});
app.use('/user', router);
英文:
Use a router
let router = express.Router();
router.get('/:id', function (req, res, next) {
console.log("Specific User Router Working");
res.end();
});
router.get('/all', function (req, res, next) {
console.log("All User Router Working");
res.end();
});
app.use('/user',router);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论