使用 axios 在 GET 中将具有多个值的参数的对象作为查询字符串传递 [英] Passing an object with a parameter with multiple values as a query string in a GET using axios

查看:72
本文介绍了使用 axios 在 GET 中将具有多个值的参数的对象作为查询字符串传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 GET 上将具有多个值的参数作为查询字符串传递是很常见的:

http://server/status?stat=a&stat=b

如何使用 JS 中的 axios 库创建这种类型的查询字符串?创建一个以参数名称为键,值为多个值的数组的对象会创建一个查询字符串:

http://server/status?stat[]=a&stat[]=b

这是服务器期望的格式不正确.可以在 axios 中完成吗?

解决方案

在 GET 上将具有多个值的参数作为查询字符串传递是很常见的

这绝不是一个标准.不同的语言、框架实现不同的解决方案.请参阅 重复 HTTP GET 查询键的权威位置.

<块引用>

这可以在 axios 中完成吗?

来自 Axios 文档:

<块引用>

在 node.js 中,你可以使用 querystring 模块如下:

var querystring = require('querystring');axios.post('http://something.com/', querystring.stringify({ foo: 'bar'});

您也可以使用 qs 库.

qs 库 支持数组.

另一种方法是使用 Connect.

更新

QS 库支持数组,但前提是参数以[] 为后缀:

var paramsString = "q=URLUtils.searchParams&topic[]=api&topic[]=bar"

或者,URLSearchParams API 提供了一个getAll() 方法:

<块引用>

var paramsString = "q=URLUtils.searchParams&topic=api"var searchParams = new URLSearchParams(paramsString);searchParams.getAll("主题");//["api"]

这在 IE 中不起作用,但是 polyfill url-search-params 可用.

It is common to pass a parameter with multiple values as a query string on a GET:

http://server/status?stat=a&stat=b

How does one create this type of query string using the axios library in JS? Creating an object where the parameter name is the key and the value is the array of multiple values creates a query string:

http://server/status?stat[]=a&stat[]=b

which is an incorrect format from what the server expects. Can this be done in axios?

解决方案

It is common to pass a parameter with multiple values as a query string on a GET

This is by no means a standard. Different languages, frameworks implement different solutions. See this question on the Authoritative position of duplicate HTTP GET query keys.

Can this be done in axios?

From the Axios documentation:

In node.js, you can use the querystring module as follows:

var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar'});

You can also use the qs library.

The qs library has support for arrays.

An alternative would be to use Connect.

Update

The QS library supports arrays, but only if the parameter is suffixed with []:

var paramsString = "q=URLUtils.searchParams&topic[]=api&topic[]=bar"

Alternatively, the URLSearchParams API offers a getAll() method:

var paramsString = "q=URLUtils.searchParams&topic=api"
var searchParams = new URLSearchParams(paramsString);

searchParams.getAll("topic"); // ["api"]

This doesn't work in IE, but the polyfill url-search-params is available.

这篇关于使用 axios 在 GET 中将具有多个值的参数的对象作为查询字符串传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆