vue axios请求两种方式,出现401错误,需要添加config配置

file文件的转化

const uint8Array = xxxxx;//总之先拿到uint8Array 格式的话
let mBuffer = Buffer.from(uint8Array); //转buffer
this.mBlob = new Blob([mBuffer], { type: 'application/pdf;charset=utf-8' }); //这里是转blob
this.mFile = new File([this.mBlob], 'merged.pdf', { type: this.mBlob.type }); //这里是转file
const url = window.URL.createObjectURL(this.mBlob); //这里是通过blob拿到url

传file文件参数


let formData = new FormData()
formData.append('file', this.mergePdfFile)
formData.append('param', JSON.stringify(this.arr))
// 创建一个配置对象,包含头部信息和请求参数
      const config = {
        headers: {
          Authorization: xxx, // 添加 Authorization 头部(注意空格)
          'Content-type': 'multipart/form-data' // 设置 Content-Type
        }
      }
    this.openLoading()
	axios
        .post(`${this.url}/xxx/xxx/xxxx`,
            formData,
            config
        )
        .then((res) => {
          console.log(res, "123123");
          

          this.closeLoading();
        })
        .catch(() => {
          this.$message.error("合并失败,请重新合并");
          this.closeLoading();
        });


///
 openLoading() {
      this.loading = this.$loading({
        lock: true,
        text: "正在同步,请勿操作",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.7)",
      });
    },
    // 关闭loading层
    closeLoading() {
      this.loading.close();
    },

另一种方式

this.openLoading()
axios({
          url: `${this.url}/xxxx/${xxx}/${xxx}/xxx/xxx`,
          method: "GET",
          responseType: "blob", //划重点了,文件下载需要注意添加responseType
          headers: {
                Authorization: xxxx,
              },
        })
          .then((res) =>  {
          console.log(res, "123123");
         
          this.closeLoading();
        })
        .catch(() => {
          this.$message.error("合并失败,请重新合并");
          this.closeLoading();
        });

你可能感兴趣的:(vue.js,javascript,ecmascript)