如何防止 Axios 对我的请求参数进行编码? [英] How to prevent Axios from encoding my request parameters?

查看:30
本文介绍了如何防止 Axios 对我的请求参数进行编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是,我注意到 Axios 在发送请求时对我的 API 密钥中的字符进行了编码.这会导致 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 对我的 GET 参数进行编码?

How can I prevent Axios from encoding my GET parameters?

推荐答案

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

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

paramsSerializer 可以在实例级别设置:

paramsSerializer can be set at the instance level:

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

或在全球层面:

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

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

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

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

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

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

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

这篇关于如何防止 Axios 对我的请求参数进行编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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