问题
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--
"
}
So I cannot get value using $_POST["username"]
below is axios setting
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'
}
}
})
How do I send data with the same format as dev + prod?
回答1:
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.
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'
}
})
来源:https://stackoverflow.com/questions/59743632/axios-post-with-react-jest