axios 크로스 문제 및 난자 해결
1978 단어 ☆ 프레임---------vue
파일 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
이메일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})