vue2项目-request配置put请求Content-Type为x-www-form-urlencoded

在项目中遇到需要使用put请求的接口, 使用的方式是x-www-form-urlencoded

在这里插入图片描述

步骤梳理—在项目的request.js文件是默认配置了json方式的

import axios from "axios"

axios.interceptors.request.use(function (config) {
    
    
	console.log(config)
    // 请求头配置带token
    const token = sessionStorage.getItem('token_kpi')
    if(token) {
    
    
        config.headers.Authorization = token
    }
    return config
}, function(error) {
    
    
    return Promise.reject(error)
})

控制台打印结果如下

在这里插入图片描述

可以看到在headers里的Content-Type为null

解决问题思路-1: 当发起put请求时, headers里的Content-Type的值需要改为application/x-www-form-urlencoded

request.js添加代码

axios.interceptors.request.use(function (config) {
    
    
    const token = sessionStorage.getItem('token_kpi')
    if(token) {
    
    
        config.headers.Authorization = token
    }
    
    if(config.method === 'put') {
    
     // 判断如果是put请求, 配置content-type
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }else {
    
    
        config.headers['Content-Type'] = 'application/json'
    }
    console.log(config)
    return config
}, function(error) {
    
    
    return Promise.reject(error)
})

这里用conifg.method判断当时put请求时,
给config.headers里面的Content-Type赋值 ‘application/x-www-form-urlencoded’

这时候config打印到控制台可以发现

在这里插入图片描述

headers里面的Content-Type的值变为application/x-www-form-urlencoded
并且其它接口请求类型不受影响

解决问题思路-2: 直接修改封装的接口api.js文件

// 修改密码
export function changePassword(data) {
    
    
  return request({
    
    
    url: 'xxx/member/updatePwd',
    headers: {
    
     // 修改请求头
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    method: 'put',
    data
  })
}

本文以学习记录为主

猜你喜欢

转载自blog.csdn.net/qq_41421033/article/details/129520799