I'm currently troubleshooting three request methods that are not functioning properly: GET, UPDATE, and DELETE for a user by _id.
When I try to run these requests in the browser or postman, I receive a "no page found" error in the API call.
The route for calling my API is http://localhost:3000/api/users, which successfully retrieves all users. However, when I attempt to access a specific user using the URL http://localhost:3000/api/users/{_id}, replacing {_id} with the actual user ID, I encounter a "no page found" issue.
Below is the code for the 3 requests:
// Function to get user by _id
export async function getUserById(req: NextApiRequest, res: NextApiResponse) {
try {
console.log('Route accessed:', req.url); // Logging the accessed route
const { id } = req.query; // Retrieving the _id parameter from the request query
// Fetching user by _id from UserModel
const user = await connectAndDisconnect(() => UserModel.findById(id as string));
if (!user) {
console.log('User not found:', id);
return res.status(404).json({ error: 'User not found' });
}
// Returning the fetched user
return res.status(200).json(user);
}
catch (error) {
console.error('Error fetching user by ID:', req.query.id, error);
return res.status(500).json({ error: 'Internal Server Error' });
}
}
// Function to update user by _id
export async function updateUserById(request: NextRequest) {
const userId = request.nextUrl.searchParams.get('_id');
const { body } = request;
if (!userId) {
return new NextResponse('Invalid user ID', { status: 400 });
}
const updatedUser = await asyncHandler(
() =>
connectAndDisconnect(() =>
UserModel.findByIdAndUpdate(userId, body as Partial<IUser>, { new: true })
),
'Error updating user by ID'
);
if (!updatedUser) {
return new NextResponse('User not found', { status: 404 });
}
const jsonUpdatedUser = JSON.stringify(updatedUser);
return new NextResponse(jsonUpdatedUser, {
headers: { 'Content-Type': 'application/json' },
});
}
// Function to delete user by _id
export async function deleteUserById(request: NextRequest) {
const userId = request.nextUrl.searchParams.get('_id');
if (!userId) {
return new NextResponse('Invalid user ID', { status: 400 });
}
const deletedUser = await asyncHandler(
() => connectAndDisconnect(() => UserModel.findByIdAndDelete(userId)),
'Error deleting user by ID'
);
if (!deletedUser) {
return new NextResponse('User not found', { status: 404 });
}
const jsonDeletedUser = JSON.stringify(deletedUser);
return new NextResponse(jsonDeletedUser, {
headers: { 'Content-Type': 'application/json' },
});
}
Here is the content of the route.ts file:
// api/users.ts
import { NextRequest, NextResponse } from 'next/server';
import { createUser, getAllUsers, getUserById, updateUserById, deleteUserById } from
'@/app/controllers/user';
import handleRequest from '@/app/middleware/handlerequest';
export async function GET(request: NextRequest) {
return handleRequest(request, {
'/api/users': getAllUsers,
'/api/users/:id': getUserById,
});
}
export async function POST(request: NextRequest) {
return handleRequest(request, {
'/api/users': createUser,
});
}
export async function PUT(request: NextRequest) {
return handleRequest(request, {
'/api/users/:id': updateUserById,
});
}
export async function DELETE(request: NextRequest) {
return handleRequest(request, {
'/api/users/:id': deleteUserById,
});
}