排查Axios POST请求后台接收不到数据的问题
前端使用Axios发送POST请求时,代码运行正常,但后端却无法接收数据,而Postman却能成功接收,这通常是由于HTTP请求的Content-Type设置不一致导致的。
例如,开发者使用Axios向/login接口发送POST请求,传递用户名en和密码password。前端代码如下:
request({ url: "/login", method: "post", data: { en: this.en, password: this.password } }).then(res => { console.log(res); });
问题根源在于Axios默认的Content-Type为application/json,而Postman可能默认使用或用户手动设置了application/x-www-form-urlencoded。这两种格式的数据传输方式不同:Axios直接发送JSON对象,而application/x-www-form-urlencoded则将数据编码成键值对的形式。
解决方法是使Axios请求的数据格式与后端期望的一致。如果后端期望application/x-www-form-urlencoded,可以使用qs库:
import axios from 'axios'; import qs from 'qs'; let data = { "en": "1234", "password": "yyyy" }; axios.post(`/login`, qs.stringify(data)) .then(res => { console.log('res=>', res); });
qs.stringify()方法将data对象转换为application/x-www-form-urlencoded格式的字符串。 如果后端期望接收JSON数据,则无需使用qs库,保持Axios默认的application/json即可。 务必确认后端代码能够正确解析接收到的数据格式。
以上就是Axios POST请求后台收不到数据是什么原因?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号