简体   繁体   中英

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

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?

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

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

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

This is a bug in Axios 1.0.0, fixed in 1.1.0

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM