简体   繁体   English

如何使用查询字符串将带有 Axios 的请求发送到 URL?

[英]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.我正在尝试将一段工作代码从 Axios 0.27.2 升级到 1.0.0,并且处理带有查询字符串的 URL 的方式似乎中断了。 That is, I get a 404 response and the actual URL used looks different than before in that the question mark is missing.也就是说,我得到一个 404 响应,实际使用的 URL 看起来与以前不同,因为缺少问号。

The URL looks like this: https://my.server.com/some/path?foo=bar&baz=abc Previous axios used that. URL 看起来像这样: https://my.server.com/some/path?foo=bar&baz=abc以前的 axios 使用它。 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在 1.0.0 版本中,错误中报告的实际发送的 URL 是: 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.类似的问题都围绕如何构建查询字符串以及 axios 为此接受参数 object 的事实展开。 In my case, I am getting a URL from elsewhere that contains / may contain a query string already.在我的例子中,我从其他地方得到一个 URL,它已经包含/可能包含一个查询字符串。 How can I convince Axios to use this URL without changing it in some way?我怎样才能说服 Axios 使用这个 URL 而不以某种方式改变它?

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

Is need to specify if is CORS REQUEST (Set axios options, before request)是否需要指定是否为 CORS REQUEST(在请求前设置 axios 选项)

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

This is a bug in Axios 1.0.0, fixed in 1.1.0这是Axios 1.0.0的bug,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 将接收到的 url 拆分为包含基数 url 和参数的对象,然后传递给 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 即可

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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