vue下使用axios的POST请求form-data的做法

2022-02-11 373点热度 0人点赞 0条评论

默认情况下我们在Vue项目中引入了axios,是哟好难过axios进行post请求,是用application/json的方式去请求的,不过可能后端API的请求方式是form-data(application/x-www-form-urlencoded)

实现方式一

package.json下增加qs:

"qs": "^6.10.1"

{
  "name": "newproject",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build"
  },
  "dependencies": {
    "axios": "^0.21.1",
    "core-js": "^3.6.5",
    "qs": "^6.10.1",
    "vue": "^2.6.11"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-plugin-vuex": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "less": "^3.0.4",
    "less-loader": "^5.0.0",
    "vue-cli-plugin-axios": "0.0.4",
    "vue-template-compiler": "^2.6.11"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}

调用:

import qs from "qs";

let payload = qs.stringify({start: 0, limit: 10, keywords: ''});
http.post('/api/info_list', payload).then(res => {
    // console.log(res)
});

实现方式二

var params = new FormData();
params.append("keywords", "");
params.append("limit", "10");
params.append("page", "0");

axios({
  method: "post",
  url: "/api/info_list",
  data: params,
  headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论