在Axios上设置标题

时间:2019-03-31 23:46:41

标签: javascript post axios

我试图在API上进行POST,但是XHR工作时Axios.post仍然失败。我知道我必须使用UTF-8设置请求的标头,但看来Axios无法识别它。

我知道我需要设置'application / x-www-form-urlencoded;我的标头请求上的charset = UTF-8'是在Flask中创建的API,所有者未配置此部分。 (并且因为它与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?

1 个答案:

答案 0 :(得分:0)

尝试下面的代码。

来自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' }
  });