Javascript 如何防止 Axios 对我的请求参数进行编码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39116731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:13:03  来源:igfitidea点击:

How to prevent Axios from encoding my request parameters?

javascriptajaxaxios

提问by Carven

I'm trying to pass in an API key through the URL parameters in my GET request.

我正在尝试通过 GET 请求中的 URL 参数传入 API 密钥。

However, I notice that Axios encodes the characters in my API key when sending the request. This causes the API to reject my request as it couldn't recognise my key.

但是,我注意到 Axios 在发送请求时对 API 密钥中的字符进行了编码。这会导致 API 拒绝我的请求,因为它无法识别我的密钥。

How can I prevent Axios from encoding my GET parameters?

如何防止 Axios 编码我的 GET 参数?

采纳答案by Nick Uraltsev

You can use a custom param serializer as follows:

您可以使用自定义参数序列化程序,如下所示:

axios.get('https://foobar.com/api', {
  paramsSerializer: function(params) {
    var result = '';
    // Build the query string 
    return result;
  }
});

paramsSerializercan be set at the instance level:

paramsSerializer可以在实例级别设置:

var instance = axios.create({ paramsSerializer: function(params) { /* ... */ } })

or at the global level:

或在全球层面:

axios.defaults.paramsSerializer = function(params) { /* ... */ };

Another option is to directly add the api key to the URL:

另一种选择是直接将 api 密钥添加到 URL:

axios.get('https://foobar.com/api?api_key=' + key);

You can add additional parameters using the `params' config option:

您可以使用 `params' 配置选项添加其他参数:

axios.get('https://foobar.com/api?api_key=' + key, {
  params: {
    foo: 'bar'
  }
});