elveti
elveti

Reputation: 2386

Change request method in axios interceptor

I'm trying to change an axios GET request into a POST request using an interceptor. The method seems to be changed, but my params are still affixed to the URL, instead of being sent in the POST body.

    axios.get(payload.url, {
      params: payload.params || {}
    })

    axios.interceptors.request.use(
      function (config) {
        // check request method -> use post if many params
        if (MY_CONDITION) {
          if (config.method === 'get') {
            console.log('changed to post')
            config.method = 'post'
          }
        }
        return config
      }
    )

Am I missing something?

Upvotes: 1

Views: 3319

Answers (1)

elveti
elveti

Reputation: 2386

Thanks to CD..'s comment, I found the solution. Params are always attached to the request-URL, while I'd need to use data, since that's what ends up in the POST body. Posting in case other's need it:

  config.method = 'post'
  config.data = config.params
  config.params = {}

Upvotes: 1

Related Questions