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

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

问题描述

通常将具有多个值的参数作为查询字符串传递给GET:

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

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

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

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

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

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

推荐答案

通常将带有多个值的参数作为查询字符串传递给GET

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

这绝不是标准.不同的语言,框架实现不同的解决方案.在重复的HTTP 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.

这可以在axios中完成吗?

Can this be done in axios?

Axios文档:

在node.js中,您可以按以下方式使用querystring模块:

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

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

您还可以使用 qs 库.

qs库支持数组.

一种替代方法是使用连接.

更新

QS库支持数组,但仅当参数后缀为[]时:

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

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

或者, URLSearchParams API 提供了方法:

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

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

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

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

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

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

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