Home > Blockchain >  How can I send a request with Axios to a URL with a query string?
How can I send a request with Axios to a URL with a query string?

Time:10-06

I am trying to upgrade a working piece of code from Axios 0.27.2 to 1.0.0 and the way a URL with a query string is handled seems to break. That is, I get a 404 response and the actual URL used looks different than before in that the question mark is missing.

The URL looks like this: https://my.server.com/some/path?foo=bar&baz=abc Previous axios used that. In the 1.0.0 version the actual URL sent, as reported in the error, is: https://my.server.com/some/pathfoo=bar&baz=abc

Similar questions all revolve around how to build a query string and the fact that axios accepts a params object for that. In my case, I am getting a URL from elsewhere that contains / may contain a query string already. How can I convince Axios to use this URL without changing it in some way?

CodePudding user response:

axios.get('my-url', {
  params: {
    foo: "baz",
    baz: "abc",
  }
}).then(...)

Is need to specify if is CORS REQUEST (Set axios options, before request)

CodePudding user response:

See https://github.com/axios/axios/issues/4999

This is a bug or breaking change (to be discussed in that ticket) in Axios 1.0.0

CodePudding user response:

You can resolve this by building a function to split the received url into objects containing a base url and params before passing to axios.

function getUrlParams (url) {
const fullUrl = url;

const splitUrl = fullUrl.split("?");

const newUrl = splitUrl[0];

const paramsArray = splitUrl[1].split("&");

let paramsObj = {};

for(let i = 0; i < paramsArray.length; i  )
{
 const arr = paramsArray[i].split("=");
 const keyName = arr[0];
 const value = arr[1];
  paramsObj = {...paramsObj, [keyName]: value};
}
const data = {
base: newUrl,
params: paramsObj
}
return data;
}


const url = getUrlParams("https://my.server.com/some/path?foo=bar&baz=abc");

console.log(url)

Then for axios call you can do

axios.post(url.base, null, { params: url.params})
  • Related