【发布时间】: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/858 和 https://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