msorr95
msorr95

Reputation: 101

req.params returns undefined (it actually returns :itemId as a string so it's kind of undefined) instead of the id

it's been a few days that I do not know what is wrong with my code and couldn't find any solution for this.

I tried also to get the id with query (moving the controllers on the shop routes and, of course, changing the : with the ?), and, also with req.body trying to get the input with the id but it didn't work.

I also tried POST and PATCH instead of GET and it didn't work

here is my code:

auth.js (controller)

exports.addToCart = async (req, res, next) => {

try {

    // getting the user id from the session so that we can find this user
    const userId = req.session.user._id.toString();

    // finding the user
    const user = await User.findById(userId);

    const itemId = req.params.itemId;

    console.log(itemId) // returns exactly :itemId as a string (so it does not return the actual item id)
    
    const item = await Item.findById(itemId);
    console.log(item); // returns an error because of course the id is wrong
    
} catch (err) {

    console.log(err);

    if(!err.statusCode) {

        err.statusCode = 500;

    }

}
};

auth.js (route)

router.get('/add-to-cart/:itemId', authController.addToCart);

and then on the frontend I first pass as props the item id to the AddToCart component like this:

Shop Component where I load all the items from the database:

                    <ItemStyle key={item._id}>

                    <h1>title</h1>
                    <p>{item.title}</p>

                    <img alt={item.title} src={item.image}></img>

                    <h1>description</h1>
                    <p>{item.description}</p>

                    <h1>price</h1>
                    <p>{item.price}</p>

                    <AddToCart itemId={item._id} />
                
                </ItemStyle>

AddToCart component:

class AddToCart extends Component {

addToCart = async () => {

    await fetch(`http://localhost:8090/auth/add-to-cart/:itemId`, {

        method: 'GET',

        headers: {

            'Accept': 'application/json',
            'Content-Type': 'application/json',

        },

        credentials: 'include',

    })

    .then(() => { 

        /* staying on the same page */
        return window.location.replace('/shop');

    })

    .catch(err => console.log(err));

}

render() {

    return(

        <form encType="application/x-www-form-urlencoded">

            <input type="hidden" name="itemId" value={this.props.itemId} />

            <button onClick={this.addToCart}>Add To Cart</button>

        </form>

    )

}

}

if I remove the type="hidden" from the input I can actually see that the right id is assigned to that item. Anyone has a solution for this? If for some reasons I am going against stackoverflow policies please let me know and I will update the question. Thank you in advance.

Upvotes: 0

Views: 226

Answers (2)

Murat Colyaran
Murat Colyaran

Reputation: 2189

I found your problem

You shouldn't use .then() and await together. I suggest you to use await only. Like this:

var response = await fetch(`http://localhost:8090/auth/add-to-cart/${itemId}`, {

    method: 'GET',

    headers: {

        'Accept': 'application/json',
        'Content-Type': 'application/json',

    },

    credentials: 'include',

});

Also, if you notice, I used ${itemId} above. If you want to set a variable in a string. You have to use it like that.

Upvotes: 1

Pankaj Tanwar
Pankaj Tanwar

Reputation: 1070

Here are a few things you should do -

  1. Remove await in side addToCart function, it should not be used with "then".

  2. Inside addToCart function, make sure you are getting itemId value.

  3. Change API end point -

    http://localhost:8090/auth/add-to-cart/${itemId}

Upvotes: 1

Related Questions