David
David

Reputation: 179

Passing parameter to a GET request to retrieve specific information

I am trying to retrieve (GET) specific information based on a parameter that is passed. My code looks like this:

In index.js:

export var comments = (userId) => { 
    return new Promise((value) => {
        axios.get('http://localhost:1000/getreviews/:userId')
        .then((response) => {
            console.log(response.data.comment);
        })
    })
}

In routes.js:

router.route('/:userId').get((req, res) => {
    Users.find({user: req.params.userId}) 
        .then((reviews) => res.json(reviews)
    );
});

So I want to get relevant information. To give a higher-level idea of what is going on--there are multiple modals, and when a specific one is clicked I want to get specific information from the database, instead of getting all the information from the database and then do the extraction of relevant information in index.js based on the user's id. That way, I will be getting all the information on every modal click which is not efficient so I want to avoid it.

Upvotes: 0

Views: 894

Answers (2)

David
David

Reputation: 179

Writing the GET request in a different way solved the issue:

axios({ 
            method: 'get',
            url: 'http://localhost:1000/getreviews/',
            params: {
                user: userId 
            })

Then I could access the userId in routes.js through req.query.user and it will give me the userId I just passed.

Upvotes: 0

Charef B
Charef B

Reputation: 437

What is the problem exactly, is Users.find({user: req.params.id}) not returning the expected value? mongoose has findById which queries the db looking for the object with that specific id, in your case :

Users.findById(req.params.userId) 
        .then((reviews) => res.json(reviews)
    );

edit: it seems like you're passing undefined as a parameter find, note that the name of the variable that is stored in params must be the same as the parameter you provided in your get method which is userId, so use req.params.userId instead.

edit2: js part

export var comments = (userId) => { 
    return axios.get(`http://localhost:1000/getreviews/${userId}`)
        .then((response) => {
            return response.data
        })

}

Upvotes: 1

Related Questions