首页
Javascript
Html
Css
Node.js
Electron
移动开发
小程序
工具类
服务端
浏览器相关
前端收藏
其他
关于
公司注册

vue使用axios进行form表单提交

2018年11月07日 发布 阅读(9303) 作者:Jerman

问题:

vue使用axios提交数据时,默认使用的是Content-Type: application/json;charset=UTF-8格式,若要使用<form>原生的形式进行数据提交,需要配置

解决:

1、添加header头是必须的,添加"Content-Type": "application/x-www-form-urlencoded"
以POST请求为例

  1. this.axios
  2. .post("/common/login", data.data, {
  3. transformRequest: [
  4. function(data) {
  5. // Do whatever you want to transform the data
  6. let ret = "";
  7. for (let it in data) {
  8. ret +=
  9. encodeURIComponent(it) +
  10. "=" +
  11. encodeURIComponent(data[it]) +
  12. "&";
  13. }
  14. return ret;
  15. }
  16. ],
  17. headers: {
  18. "Content-Type": "application/x-www-form-urlencoded"
  19. }
  20. })
  21. .then(function(res) {
  22. })
  23. .catch(function(error) {
  24. console.log(error);
  25. });

2.1 使用transformRequest进行数据转让,如1中的代码
参考:https://www.npmjs.com/package/axios

2.2 使用qs进行数据转换,qs在安装axios时会默认安装,不用再重新安装,直接引入即可

  1. import qs from "qs";
  2. //...省略
  3. this.axios
  4. .post("/common/login", qs.stringify(data.data), {
  5. headers: {
  6. "Content-Type": "application/x-www-form-urlencoded"
  7. }
  8. })
  9. .then(function(res) {
  10. })
  11. .catch(function(error) {
  12. console.log(error);
  13. });
版权声明:本站文章除特别声明外,均采用署名-非商业性使用-禁止演绎 4.0 国际 许可协议,如需转载,请注明出处