【问题标题】:Set header on Axios [duplicate]在 Axios 上设置标题 [重复]
【发布时间】:2019-08-22 02:37:31
【问题描述】:

我正在尝试在 API 上发布,但 Axios.post 一直失败,而 XHR 工作。我知道我必须使用 UTF-8 设置请求的标头,但 Axios 似乎无法识别它。

我知道我需要设置 'application/x-www-form-urlencoded;我的标头请求中的 charset=UTF-8' 是 API 是在 Flask 中制作的,并且所有者没有配置这部分。 (而且因为它适用于 XHR)。

工作代码是:

const post = (url, params) => {
    const http = new XMLHttpRequest();
    http.open("POST", url, true);

    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
    http.onreadystatechange = () => {
        if(http.readyState == 4 && http.status == 200) {
            alert(http.responseText);
        }
    }

    http.send(params);
};

所以我用谷歌搜索知道如何将#setRequestHeader 转换为 Axios.post() 并找到以下链接:https://github.com/axios/axios/issues/858https://github.com/axios/axios/issues/827

然后我尝试了这样的事情:

const headers = {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
};

const post = ({ data, endpoint }) => axios
    .post(endpoint, data, { headers })
    .then(request => request.data);

这个:

const headers = {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
};

const post = ({ data, endpoint }) => axios
    .post(endpoint, data, headers)
    .then(request => request.data);

还有这个:

const headers = {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
};

const post = ({ data, endpoint }) => axios({
    method: "post",
    url: endpoint,
    data,
    headers
}).then(request => request.data);

但是随后每一个都失败并出现错误 400。 那么,我应该如何将 http.setRequestHeader() 翻译成 Axios 呢?

【问题讨论】:

  • 问题可能是你的data。它到底是什么?
  • 你在使用拦截器吗?你可能想看看this bug
  • 仅供参考,您的第一次尝试最接近正确,因为您需要将标题放在 headers 键下
  • 嗨,@Phil。数据是这样的对象:{ text: "this is a text" }.
  • 这就是我的怀疑。请参阅链接的重复问题。另请参阅 Axios 文档 ~ github.com/axios/…

标签: javascript post axios


【解决方案1】:

试试下面的代码。

来自https://github.com/axios/axios/issues/858

const endpoint = 'http://localhost/test.php'; // eg.

axios.post(endpoint,
  querystring.stringify({
        paramter: 'value',          
}),
  {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
  });

【讨论】:

  • 这里没有什么可以将你的 { firstName: this.name } 对象序列化为 application/x-www-form-urlencoded 所以这不起作用
  • 你是对的,我会改变答案。谢谢!
猜你喜欢
  • 2018-09-21
  • 1970-01-01
  • 2018-04-08
  • 2019-06-15
  • 2022-01-27
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多