Home > Enterprise >  Parameters not being passed to server router
Parameters not being passed to server router

Time:03-22

I have this function where I pass some parameters to my server:

async function createOrderItemForCardInList(cardID, value, listID) {
    const token = await getToken();
    const response = await fetch(`${basePath}/order/list/${listID}`, {
        method: 'POST',
        body: JSON.stringify({
            cardID,
            value
        }),
        headers: getTokenAuthHeaders(token)
    });

    return response.json();
}

And on my server, I have the route defined for when the call is passed:

router.post('/list/:id', TokenController.isAValidToken, async (req, res) => {
    const { cardID, value } = req.query;
    console.log(value, cardID); // <- This prints 'undefined'

    try {
        const orderItem = await OrderItemController.createOrderItem(value, req.params.id, cardID);
        res.json(orderItem);
    } catch (error) {
        ErrorController.errorCallback(error, res);
    }
});

As you can see by the commentary on my router, the parameters of que request are not being passed, how can I resolve this?

I know for a fact that the parameters print their correspondent values when I place a console.log(cardID, value, listID) on the createOrderItemForCardInList function.

CodePudding user response:

You are destructing a query which are added after a ? in a request. IE .com?cardID=777&value=10000

However in your original code you send it via the POST body. Change req.query to req.body to achieve the intended result.

router.post('/list/:id', TokenController.isAValidToken, async (req, res) => {
    const { cardID, value } = req.body;
    console.log(value, cardID); // <- This prints 'undefined'

    try {
        const orderItem = await OrderItemController.createOrderItem(value, req.params.id, cardID);
        res.json(orderItem);
    } catch (error) {
        ErrorController.errorCallback(error, res);
    }
});
  • Related