0

I have a situation , where i have to send some data to server with query strings.

import * as actions from './actions';
import AXIOS from 'services/axios';

export function getLastEvent({campaign_name, with_campaign} = {}) {
    return dispatch => {

        return AXIOS.get(`/events/last-event?${campaign_name && `campaign_name=${campaign_name}`}&${with_campaign && `with_campaign=${with_campaign}`}`)
            .then(response => dispatch(actions.getLastEventResponse(response)));
    };
}

And also i have to check it with express-validator in my backend.

router.get('/last-event', roleChecker('customer'), [
    query('with_campaign').optional().isBoolean(),
    query('campaign_name').optional(),
], async (req, res, next) => {
    try {
        // .... some actions
        return res.status(OK).send(result);
    } catch (err) {
        next(err);
    }
});

As you can see , i am validating with_campaign if it is Boolean. From my client side there are cases that i don't send with_campaign option. How to best structure my URL not to be such a long ? And if i don't have both properties , then i am getting an URL like this

localhost:3000?&

Norayr Ghukasyan
  • 1,298
  • 1
  • 14
  • 28
  • Possible duplicate of [How to create query parameters in Javascript?](https://stackoverflow.com/questions/111529/how-to-create-query-parameters-in-javascript) – ponury-kostek Dec 03 '18 at 11:27
  • Don't manually build the query string, use a library to handle that for you so you don't have awkward URLs such as `localhost:3000?&`: https://github.com/axios/axios#nodejs – Cisco Dec 03 '18 at 12:14
  • Which library do you advise ? – Norayr Ghukasyan Dec 03 '18 at 15:16

0 Answers0