Axios post with react + jest

最后都变了- 提交于 2020-03-26 03:51:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!