Axios发布与React +开玩笑 [英] Axios post with react + jest
问题描述
在开发和生产时,服务器端(PHP)位于数组下方
when development + production, server-side(PHP) gets below array
array(2) {
["username"]=>
string(8) "abc12345"
["password"]=>
string(6) "1111"
}
但是如果我开玩笑地测试
but if I test with jest
["----------------------------366071262138387187326757
Content-Disposition:_form-data;_name"]=>
string(193) ""username"
abc12345
----------------------------366071262138387187326757
Content-Disposition: form-data; name="password"
1111
----------------------------366071262138387187326757--
"
}
所以我无法使用$ _POST ["username"]
So I cannot get value using $_POST["username"]
以下是axios设置
const FormData = require("form-data")
let bodyFormData = new FormData();
bodyFormData.append('username', values.login);
bodyFormData.append('password', values.password);
return await axios({
method: 'post',
url: url,
data: bodyFormData,
config: {
headers: {
'Content-Type': 'multipart/form-data'
}
}
})
如何发送与dev + prod相同格式的数据?
How do I send data with the same format as dev + prod?
推荐答案
请勿将FormData
用于简单形式的POST.它要求使用multipart/form-data
Content-Type,它相当复杂,通常在上传文件而不是典型的表单数据时使用.
Don't use FormData
for a simple form POST. It requires.the use of the multipart/form-data
Content-Type which is fairly complex, and typically used when uploading files rather than typical form data.
我想您的服务器应该是application/x-www-form-urlencoded
,因此请尝试:
I presume your server would be expecting application/x-www-form-urlencoded
, so try:
const qs = require('querystring');
...
const data = qs.stringify({
username: values.login,
password: values.password
});
return await axios.post(url, data, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
这篇关于Axios发布与React +开玩笑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!