vue的axios请求报415错误,后台为springboot接

2021-02-08  本文已影响0人  尘埃里的玄

前端代码:

        handleUpload(formName: any){
            let data = (this.$refs[formName] as any).model;
            let p ={fileName:data.fileName,fileType:data.fileType,createPerson:data.createPerson}
            this.API_SERVICE.insertReport(p)
                .then( (res) =>{
                    console.log(res);
                })
                .catch((res) =>{
                    console.log(res);
                })
                .finally()
        }

  insertReport(params: any){
    let url = `/report/reportDesign/insertReportFile`
    return service.post(url,params)
  }
}

后台代码:

@RestController
@Api(tags = "用于报表设计接口")
@RequestMapping("/report/reportDesign")
public class ReportFileController {
    @Autowired
    ReportFileService reportFileService;
    @PostMapping("/insertReportFile")
    public Result insertReportFile(@RequestBody HashMap<String,Object> params){
        int i = reportFileService.insertReportFileInfo(params.get("fileName").toString(), Integer.valueOf(params.get("fileType").toString()), params.get("createPerson").toString());
        if (i == 1)
            return new Result(true,"insert  successful",i);
        return new Result(false,"insert failed",i);
    }

}

发现一直请求为415错误
我就开始怀疑是contenttype格式的问题
最后调到前端项目代码的service中发现:

 * Created by tulang on 2019/9/27.
 * axios http请求拦截配置
 */
import axios from "axios";
import { Message, Notification } from "element-ui";
import { getToken, getTokenType } from "@/utils/auth";
import router from "./../router";
import CONFIG from "@/api/config";
const isProduction = process.env.NODE_ENV === "production";
let instance = axios.create();
//POST请求格式为'application/json'的API白名单
let postJsonApiWhiteList = ["/meteStyle/add", "/meteStyle/edit", "/dosageModel/submitAreaDetail", "/dosageModel/submitAreaDetailWater" ]
instance.defaults.withCredentials = true; //让ajax携带cookie
// instance 配置
instance.defaults.timeout = 30000; //30s timeout
instance.defaults.baseURL = CONFIG.url.http;
//设置post,put请求头部数据格式
instance.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";
instance.defaults.headers.put["Content-Type"] =
  "application/x-www-form-urlencoded";

//序列化post请求参数
let serializePostParams = (obj: any) => {
  let temp: Array<any> = [];
  if (!obj || typeof obj !== "object") {
    return obj;
  }
  Object.keys(obj).map(key => {
    if (obj[key] || obj[key] == 0) {
      temp.push(`${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`);
    }
  });
  return temp.join("&");
};

// http请求 request 拦截器
instance.interceptors.request.use(
  (config: any) => {
    if (!config.url) {
      config.url = "/noauth/unitInformation";
    }
    if ((config.url.indexOf('/oauth') > -1 ) || (config.url.indexOf('/user') > -1 )) {
      config.headers.Authorization = `${getTokenType()} ${getToken()}`;//getTokenType()后面有空格!!!;
      config.baseURL = process.env.NODE_ENV === "development" ? CONFIG.url.http+"/auth/" : CONFIG.url.http+"/auth/";
    }else if((config.url.startsWith('/task')) || (config.url.startsWith('/message')) || (config.url.startsWith('/auth')) || (config.url.startsWith('/report'))){
  config.baseURL = CONFIG.url.http;
    }else{
      config.baseURL = CONFIG.url.http + "/api";
    }
    //针对put,post请求,处理提交的数据
    if (config.method === "post" || config.method === "put") {
      if (postJsonApiWhiteList.includes(config.url)) {
        config.headers["Content-Type"] = "application/json";
      } else {
        config.data = serializePostParams(config.data);
      }
    }
    return config;
  },
  (err: any) => {
    return Promise.reject(err);
  }
);

// http返回 response 拦截器
instance.interceptors.response.use(
  (response: any) => {
    let code = response.data.code;
    switch (Number(code)) {
      case 403:
        //没有权限
        Notification({
          title: "错误",
          message: CONFIG.code[code],
          type: "error",
          duration: 3000,
          showClose: true,
          position: "bottom-right",
          customClass: "notifiy-error"
        })
        break;
      case 412:
        //没有token
        Notification({
          title: "错误",
          message: CONFIG.code[code],
          type: "error",
          duration: 3000,
          showClose: true,
          position: "bottom-right",
          customClass: "notifiy-error",
          onClose() {
            router.push({
              path: "/"
            })
          }
        })
        break;
      case 413:
        //token无效
        Notification({
          title: "错误",
          message: CONFIG.code[code],
          type: "error",
          duration: 3000,
          position: "bottom-right",
          showClose: true,
          customClass: "notifiy-error",
          onClose() {
            router.push({
              path: "/"
            })
          }
        })
        break;
      default:
        break;
    }
    return response.data;
  },
  (error: any) => {
    console.info(new Error(error), "logger");
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
      showClose: true
    });
    return Promise.reject(error);
  }
);
//给axios创建的实例添加all方法;
Object.assign(instance, { all: axios.all });
export default instance;

发现是 image.png

x-www-form-urlencoded


image.png image.png

axios默认是application/json

参考网址:https://www.pianshen.com/article/7286338071/

上一篇 下一篇

猜你喜欢

热点阅读