In my index.js
file
app.use('/api/v1/users', userRouter)
In Router file
router.get("/:id", getUserDataById);
In postman:
My GET URL looks like this: http://localhost:3000/api/v1/users?id=120622
Error it gives:
Cannot GET /api/v1/users
I think, this is how query param should be given according to the docs and tutorials i followed, but this error won't go away.
If i remove query, then other endpoints work perfectly.
I am not able to catch what's going wrong here.
I am stuck with this from last 2 days. Just a hint to resolve this, will help me a lot.
Thanks in advance!
CodePudding user response:
Firstly your index.js
and routes.js
file is fine now you just need to send request correctly see the req.params is different and the req.query is different
First Way with (Query)
In postman:
http://localhost:3000/api/v1/users?id=120622
Your Index.
app.use('/api/v1/users', userRouter);
In Router file.
router.get("/", getUserDataById);
How did you get that id;
let id = req.query.id;
Second Way with (Params) - Look at the postman URL carefully and at Route
In postman:
http://localhost:3000/api/v1/users/120622
Your Index.
app.use('/api/v1/users', userRouter);
In Router file.
router.get("/:id", getUserDataById);
How did you get that id;
let id = req.params.id;
This is the two-way you can get your id, Let me know if you have any more questions and I'll try to clarify your points with more clarity.
CodePudding user response:
You are not calling API correctly inside the Postman. You should call it like this:
http://localhost:3000/api/v1/users/120622
CodePudding user response:
I think you are not connect your user router to your index.js router i send y sample for you and i hope your problem solved :)
// Packages
import express from 'express';
const router = express.Router();
// Routes
import {publicRouter} from "./public";
router.use('/api', publicRouter);
export {router as Router};
and my public router :
import express from 'express';
import {authRouter} from "./auth";
// Packages
const router = express.Router();
router.use('/auth', authRouter);
export {router as publicRouter};
and my auth Router :
import express from 'express';
import passport from 'passport';
const router = express.Router();
import registerController from "../../controllers/auth/RegisterController";
import loginController from "../../controllers/auth/LoginController";
import userControllerfrom "../../controllers/users/UsersController";
router.post('/register', registerController.process);
router.post('/login', loginController.process);
router.get('/users/:id', userController.getUser);
export {router as authRouter};
CodePudding user response:
In the router file, what you are using is Route Parameter where the valid URL would be http://localhost:3000/api/v1/users/120622
. for your Postman api to work you should remove :id
at router file