Patrick
Patrick

Reputation: 37

req.params.userId not found ( path set to /:userId) Node.js

I want to get an user by his userId parameter but it doesn't work. The app connects to the database(Atlas), I can create users, retrieve them all in bulk but I can't retrieve them with a specific parameter ( in this case UserId), producing a not found error message.

UserRoutes.js

const express = require('express');
const UserModel = require('../models/UserModel');
const app = express();

app.get('/getusersById/:userId', async (req, res) => {

const user = await UserModel.find(req.params.userId);

try {
res.send(user);
} catch (err) {
res.status(500).send(err);
}
});

UserModel.js

const mongoose = require('mongoose');

// Define Schema
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
},

age: {
    type:Number,
    required:true
  },

userId: {
    type:String,
    required:true
  },
});


//
const User = mongoose.model('user', UserSchema);
module.exports = User;

Server.js

// Open connection to test database

const express = require('express');
const mongoose = require('mongoose');
const UserRouter = require('./routes/UserRoutes.js');

const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

const uri = "mongodb+srv://[email protected]/dbusers?retryWrites=true&w=majority";

mongoose.connect(uri,{
userNewUrlParser: true,
useUnifiedTopology: true
});

// Notify if connection was succesful

var db = mongoose.connection;
db.on ('error', console.error.bind(console, 'connection error'));
db.once('open', function() {

console.log("Connection Succesful");

});
db.on('close', () => {
db.removeAllListeners();
});

// Router & Port

app.use(UserRouter);
app.listen(3000,
() => {console.log('Server is running...')});

And this is the postman request:

Postman get userId

Upvotes: 0

Views: 2056

Answers (3)

Sandeep Patel
Sandeep Patel

Reputation: 5148

I think you are new to API development. From the image that I can see that you are sending userId as a query parameter. But in code, you are doing req.parms.userId which is used for path params. In your code you defined route for path parameter so the request should be like this:

/getusersById/3

And to be handled as below

 app.get('/getusersById/:userId', async (req, res) => {
 const user = await UserModel.find(req.params.userId );

However, If you want to pass userId in query parameter then do this:

app.get('/getusersById', ...)

request can be made like this:

/getusersById/?userId=3

and query parameter will be accessible as below:

 app.get('/getusersById', async (req, res) => {
 const user = await UserModel.find(req.query.userId );

Read this: Query vs Path params

Upvotes: 1

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

Your request is wrong. You defined your path as:

app.get('/getusersById/:userId', /* callback */)

So the request URL should be:

/getusersById/3

and not

/getusersById/?userId=3

Upvotes: 1

Ray
Ray

Reputation: 1676

'/getusersById/:userId'

What you are doing here is parameters of your request, which is userId

the correct usage of this api is /getusersById/3

app.get('/getusersById/:usersId', async (req, res) => {

const user = await UserModel.find(req.params.usersId );

However it seems you want to use ?usersId=3 for query the user id

You need to use req.query.usersId

app.get('/getusersById', async (req, res) => {

const user = await UserModel.find(req.query.usersId );

You can find examples of query usage : https://coderrocketfuel.com/article/handle-get-request-query-string-parameters-in-express-js

Upvotes: 1

Related Questions