post请求设置表单form-data格式的几种方式

x33g5p2x  于2022-05-11 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(667)

我用默认的post方法发送数据的时候发现后端获取不到数据,然而在network中看到参数是的确传出去的了。而且用postman测试的时候也是可以的,比较了下两个的不同发现是postman使用的是form-data格式,于是用form-data格式再次请求,发现OJBK

这两种格式都是无法使用的:

方法一:配置transformRequest

缺点:其他请求格式的数据也会被重新格式化(PUT,PATCH)

  1. import axios from "axios" //引入
  2. //设置axios为form-data
  3. axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  4. axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded';
  5. axios.defaults.transformRequest = [function (data) {
  6. let ret = ''
  7. for (let it in data) {
  8. ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
  9. }
  10. return ret
  11. }]
  12. //然后再修改原型链
  13. Vue.prototype.$axios = axios

还有这种直接引用的方式:

  1. axios({
  2. method: 'post',
  3. url: 'http://localhost:8080/login',
  4. data: {
  5. username: this.loginForm.username,
  6. password: this.loginForm.password
  7. },
  8. transformRequest: [
  9. function (data) {
  10. let ret = ''
  11. for (let it in data) {
  12. ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
  13. }
  14. ret = ret.substring(0, ret.lastIndexOf('&'));
  15. return ret
  16. }
  17. ],
  18. headers: {
  19. 'Content-Type': 'application/x-www-form-urlencoded'
  20. }
  21. })

方法二:添加请求拦截器,对症下药(推荐)

所有主要浏览器都支持 encodeURIComponent() 函数

在封装好的axios里添加以下代码:

  1. //添加请求拦截器
  2. axios.interceptors.request.use(
  3. config => {
  4. //设置axios为form-data 方法2
  5. if (config.method === 'post') {
  6. let data = ''
  7. for (let item in config.data) {
  8. if (config.data[item])
  9. data += encodeURIComponent(item) + '=' + encodeURIComponent(config.data[item]) + '&'
  10. }
  11. config.data = data.slice(0, data.length - 1)
  12. }
  13. return config;
  14. },
  15. error => {
  16. console.log("在request拦截器显示错误:", error.response)
  17. return Promise.reject(error);
  18. }
  19. );

这是现在的格式

相关文章