axios解决跨域问题及乱码问题

1.跨域问题

在文件vue.config.js中写入

module.exports = {
  configureWebpack: {
    devServer: {
      proxy: {
        // proxy all requests starting with /api to jsonplaceholder
        "/api": {
          target:
            "https://movie.douban.com/j/search_tags?type=movie&source=index", //代理接口
          changeOrigin: true,
          pathRewrite: {
            "^/api": "/" //代理的路径
          }
        }
      }
    }
  }
};

以 /api 代替 https://movie.douban.com/j/search_tags?type=movie&source=index

在main.js中写入:

import axios from "axios";

Vue.prototype.$axios = axios
//在方法里,使用 this.$axios.get(url)

使用:

 async getdata() {
      try {
        const response = await this.$axios.get("/api");
        this.sum = response.data.tags;
      } catch (error) {
        // 错误处理
      }
    }

注意:这个方法在开发期间有效 !!!

2.乱码处理

由于后端取到的数据是gbk格式,axios默认response得到的是utf-8


  async getdata() {
      try {
        const response = await this.$axios.get("/api", {
          responseType: "blob",
          transformResponse: [
            function(data) {
              let reader = new FileReader();
              reader.readAsText(data, "GBK");
              reader.onload = function(e) {
                console.log(reader.result);
              };
              return reader.result;
            }
          ]
        });
        this.sum = response.data.tags;
      } catch (error) {
        // 错误处理
      }
    }

但是,这个方式存在一个问题,FileReader是异步的。

function uploadFile(file) { 
    return new Promise(function(resolve, reject) {
    let reader = new FileReader()
    reader.readAsArrayBuffer(file)
    reader.onload = function() {
        resolve(this.result)
        }
    })
}
uploadFile(file).then(function(result){//处理 result})

 

你可能感兴趣的:(☆框架,---------vue)